如何在 Laravel 8 中注册自定义异常处理程序

Sar*_*med 0 exception httpexception laravel laravel-8

在 Laravel 7 中,这段代码工作正常。usingrenderable方法也适用于 laravel 8。但我不确定如何在创建CustomException类后在 laravel 8 中注册它。

    public function render($request, Exception $exception)
    {
        if ($exception instanceof ValidationException) {
            if ($request->expectsJson()) {
                return response('Sorry, validation failed.', 422);
            }
        }

        return parent::render($request, $exception);
    }
Run Code Online (Sandbox Code Playgroud)

小智 6

这对我有用。

注册方式

   public function register()
   {
        $this->renderable(function(Exception $e, $request) {
            return $this->handleException($request, $e);
        });
    }

Run Code Online (Sandbox Code Playgroud)

handleException 的内容

 public function handleException($request, Exception $exception)
 {
     if($exception instanceof RouteNotFoundException) {
        return response('The specified URL cannot be  found.', 404);
     }
 }
Run Code Online (Sandbox Code Playgroud)

我希望你会发现它很有用。