laravel 修改api返回默认的异常处理

 

默认如果使用api请求创建或者获取如果使用了改模型的Request来验证的话,如果被rule挡掉,会返回404,而不会返回错误信息。
修改后匹配所有api/*请求的返回:

//app/Exceptions/Handler.php
    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        //如果路由中含有“api/”,则说明是一个 api 的接口请求
        if($request->is("api/*")){
            //如果错误是 ValidationException的一个实例,说明是一个验证的错误
            if($exception instanceof ValidationException){
                $result = [
                    "code"=>422,
                    //这里使用 $exception->errors() 得到验证的所有错误信息,是一个关联二维数组,所以使用了array_values()取得了数组中的值,而值也是一个数组,所以用的两个 [0][0]
                    "msg"=>array_values($exception->errors())[0][0],
                    "data"=>""
                ];
                return response()->json($result);
            }
        }
        return parent::render($request, $exception);
    }

posted on 2021-03-12 15:29  刘应杰  阅读(276)  评论(0编辑  收藏  举报

导航