zoukankan      html  css  js  c++  java
  • laravel 修改api返回默认的异常处理

     

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

    //app/Exceptions/Handler.php
        /**
         * Render an exception into an HTTP response.
         *
         * @param  IlluminateHttpRequest  $request
         * @param  Exception  $exception
         * @return IlluminateHttpResponse
         */
        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);
        }
  • 相关阅读:
    图片音乐 上传、下载
    表格类型数据,Excel csv导入,导出操作
    逐行读取txt文件,分割,写入txt。。。上传,下载
    性能分析四
    性能分析三
    postman断言
    postman+Newman语法参数
    shell_03
    shell_02
    shell_01
  • 原文地址:https://www.cnblogs.com/mouseleo/p/14524226.html
Copyright © 2011-2022 走看看