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);
        }
  • 相关阅读:
    flask框架-wtforms
    flask框架-蓝图
    flask框架-请求扩展
    flask框架-中间件
    flask框架-闪现
    flask框架-session
    flask框架-请求和响应
    flask框架-模板语言
    flask框架-路由
    flask框架-配置文件
  • 原文地址:https://www.cnblogs.com/mouseleo/p/14524226.html
Copyright © 2011-2022 走看看