首页 > 解决方案 > 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);
    }
}

标签: laravelerror-handlingtry-catchmiddlewarelaravel-6

解决方案


查看源代码,您需要捕获 \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);
    }
}

推荐阅读