CPB*_*B07 2 coldfusion try-catch
我有一个具有12步登录过程的API.登录大部分时间都成功,但现在又一次都会抛出错误(通常与JSON解析失败有关),这就是尝试的结束.
我从来没有使用过CFTry,但是从阅读过它并查看了例子后我仍无法找到这个问题的答案......
是否可以将整个登录脚本放在CFTry块中,并尝试执行脚本,直到帐户成功登录为止?
<cftry>并不像你想象的那样真正起作用.但是当它与<cfloop>和正确使用渔获物结合使用时,它仍然可以用于这种情况.
我有一个类似的问题,我需要检查3个身份验证服务器.如果第一个失败则检查第二个,如果第二个失败则检查第三个.我通过循环实现了这一点.
现在,我当然不建议你"尝试直到成功",除非你喜欢在出现意外情况时让你的服务器瘫痪的想法.但是你可以做类似伪CFML的事情.
<cfloop from="1" to="3" index="authIndex">
<cftry>
<!--- Check JSON parsing result --->
<cfif NOT isJSON(jsonData)>
<cfthrow type="badJSON" message="JSON Parsing failure" />
<cfelse>
<cfset userData = deserializeJSON(jsonData) />
</cfif>
<cfif authUser(userData.userInfo, userData.userpassword)>
<cfset session.user = {} />
<cfset session.user.auth = true />
<!--- whatever other auth success stuff you do --->
<cfelse>
<cfthrow type="badPassOrUsername" message="Username of password incorrect" />
</cfif>
<!--- If it makes it this far, login was successful. Exit the loop --->
<cfbreak />
<cfcatch type="badPassOrUsername">
<!--- The server worked but the username or password were bad --->
<cfset error = "Invalid username or password" />
<!--- Exit the loop so it doesn't try again --->
<cfbreak />
</cfcatch>
<cfcatch type="badJSON">
<cfif authIndex LT 3>
<cfcontinue />
<cfelse>
<!--- Do failure stuff here --->
<cfset errorMessage = "Login Failed" />
<cflog text="That JSON thing happened again" />
</cfif>
</cfcatch>
</cftry>
</cfloop>
Run Code Online (Sandbox Code Playgroud)
上面的代码将: - 只有在用户名或密码错误时才尝试一次 - 如果发生JSON解析数据,最多会尝试三次. - 只会尝试尽可能多的次数.一旦它返回正确的JSON响应,它应该是auth还是noten并继续.
| 归档时间: |
|
| 查看次数: |
300 次 |
| 最近记录: |