laravel - Try catch 在 Laravel 中间件中无法正常工作?
问题描述
在中间件中使用 try catch 覆盖默认异常处理程序时,它不起作用。异常没有被捕获。
class NotWorkingTryCatchMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
try {
if ( somethingThatCouldThrowAnException() ) {
$request->newVariable = true;
}
} catch (\Exception $e) {
dd('Never gets ran, Laravel default handler overrides');
}
return $next($request);
}
}
解决方案
查看源代码,您需要捕获 \Throwable 以使您的 try catch 在中间件中正常工作。\Throwable 是一个非常广泛的包罗万象,理想情况下,您将 try catch 块用于不需要考虑其错误的代码。这适用于 Laravel 5.8
class TryCatchMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
try {
if ( somethingThatCouldThrowAnException() ) {
$request->newVariable = true;
}
} catch(\Exception $e) {
// do nothing
} catch (\Throwable $e) {
// do nothing
}
return $next($request);
}
}
推荐阅读
- windows - 如何在 Windows 上更改 Macroquad Rust 框架的任务栏图标和标题?
- c++ - 为 K 排序数组问题编译此代码时出错
- node.js - 当查询参数值中包含 URL 时,nginx 代理会抛出 403 禁止
- java - 将设备或应用程序连接到 localhost:port 上的 socks4 服务器
- python - 如何删除 PYPDF2 输出 pdf 中的蓝色字段框?
- java - BiPredicate lambda 导致 java.lang.VerifyError:操作数堆栈上的类型错误,我该如何解决?
- javascript - 如何将数据道具传递给“单元”表单和 v-model?
- json - 如何使用对象在 JSON 模式中创建一个或多个选项?
- javascript - 坚持从javascript中的数组中提取信息
- azure - 如何在 Azure CLI 或 Bash 脚本中获取天蓝色存储帐户的大小?