如何解决在本地捕获exception的“抛出”?

在处理REST API调用的这个函数中,任何处理部分请求的被调用的函数都可能会抛出一个错误来指示错误代码应该作为响应发送。 但是,函数本身也可能发现一个错误,在这一点上它应该跳入exception处理块。

static async handleRequest(req) { try { let isAllowed = await checkIfIsAllowed(req); if (!isAllowed) { throw new ForbiddenException("You're not allowed to do that."); } let result = await doSomething(req); // can also raise exceptions sendResult(result); } catch(err) { sendErrorCode(err); } } 

Webstorm将突出显示以下消息: 'throw' of exception caught locally. This inspection reports any instances of JavaScript throw statements whose exceptions are always caught by containing try statements. Using throw statements as a "goto" to change the local flow of control is likely to be confusing. 'throw' of exception caught locally. This inspection reports any instances of JavaScript throw statements whose exceptions are always caught by containing try statements. Using throw statements as a "goto" to change the local flow of control is likely to be confusing.

但是,我不确定如何重构代码以改善情况。

我可以将catch块中的代码复制到if检查中,但是我相信这会使我的代码变得不易读,也难以维护。

我可以编写一个新的函数来执行isAllowed检查,如果不成功,就会抛出一个exception,但这似乎是回避了这个问题,而不是修复Webstorm应该报告的devise问题。

我们是否以一种不好的方式使用exception,这就是为什么我们遇到这个问题,或者是Webstorm错误只是误导,应该被禁用?

如果isAllowed失败,您正在检查某些内容并抛出exception,但是您知道该怎么做 – 请调用sendErrorCode 。 如果您不知道如何处理这种情况,例如在特殊情况下,您应该向外部来电者提出例外情况。

在这种情况下,如果发生这种情况,你已经有了一个定义好的过程 – 直接使用它,而不需要间接的throw / catch:

 static async handleRequest(req) { try { let isAllowed = await checkIfIsAllowed(req); if (!isAllowed) { sendErrorCode("You're not allowed to do that."); return; } let result = await doSomething(req); // can also raise exceptions sendResult(result); } catch(err) { sendErrorCode(err); } } 

我可以将catch块中的代码复制到if检查中,但是我相信这会使我的代码变得不易读,也难以维护。

相反,如上所述,我认为这是处理这种情况的方法。

这可能会给你一些提示,也许这可能是原因(不确定是否相关)。 Catch语句不捕获抛出的错误

“你的try catch块失败的原因是因为ajax请求是asynchronous的,try catch块将在Ajax调用之前执行并发送请求本身,但是当返回结果时抛出错误,AT A LATER POINT IN时间。

当try catch块被执行时,没有错误。 当错误被抛出时,没有尝试捕获。 如果您需要尝试捕获Ajax请求,请始终将ajax try catch块放在成功callback中,绝对不要在其外面。