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

问题描述

在Laravel 7中,此代码可以正常工作。在Laravel 8中也可以使用renderable方法。但是,我不确定在创建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);
    }

解决方法

文档也让我有些困惑。试试这个:

public function register()
{
    $this->renderable(function (ValidationException $e,$request) {
        if ($request->expectsJson()) {
           return response('Sorry,validation failed.',422);
        }
    });
}
,

这对我有用。

注册方法

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

handleException的内容

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

希望您会发现它有用。

,

我在 Laravel 8 上使用这个

    public function register()
    {

        $this->reportable(function (Throwable $e) {

        });

        $this->renderable(function (Throwable $e) {
            return $this->handleException($e);
        });
    }

来源: https://tony-stark.medium.com/laravel-8-error-handling-upgraded-2021-1ea9afcc2e95

,

试试这个

public function register()
{
    $this->renderable(function(\Illuminate\Validation\ValidationException $e,$request) {
        return response()->json([
            'result' => 1,'errors' => $e->errors()
        ],200);
    });
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...