• Laravel8 自定义 validate 响应


    原因

    在新某项目开发中遇到一个问题:laravel 的验证方法会自动处理验证响应
    比如登录方法:

      public function login(Request $request)
      {
          $request->validate([
              'username' => 'required|string',
              'password' => 'required|string',
          ]);
      }
    

    验证失败时响应:

    // status 422
    {
        "message": "The given data was invalid.",
        "errors": {
            "username": [
                "The username field is required."
            ],
            "password": [
                "The password field is required."
            ]
        }
    }
    
    • 当时和前端商议自定义 status 就是在http body 的json 中加一个code状态,每次响应都是http 200
    • 查阅资料后发现只要在 Exceptions 添加对应 exception 的处理方法就ok了

    修改方法:

    • 修改文件:app/Exceptions/Hander.php
    • 在 function register() 中添加 renderable 方法
    <?php
    
    namespace AppExceptions;
    
    use IlluminateFoundationExceptionsHandler as ExceptionHandler;
    
    class Handler extends ExceptionHandler
    {
        /**
         * A list of the exception types that are not reported.
         *
         * @var array
         */
        protected $dontReport = [
            //
        ];
    
        /**
         * A list of the inputs that are never flashed for validation exceptions.
         *
         * @var array
         */
        protected $dontFlash = [
            'password',
            'password_confirmation',
        ];
    
        /**
         * Register the exception handling callbacks for the application.
         *
         * @return void
         */
        public function register()
        {
            //
            // $this->renderable(function (CustomException $e, $request) {
            //     return response()->view('errors.custom', [], 500);
            // });
            $this->renderable(function (ValidationException $e, $request) {
                return response(['code' => ResultCode::PARAM_INVALID, "error" => $e->errors()]);
            });
    
        }
    }
    
    
    

    修改后响应:

    // status:200
    {
        "code": 10001,
        "error": {
            "username": [
                "The username field is required."
            ],
            "password": [
                "The password field is required."
            ]
        }
    }
    
  • 相关阅读:
    nyoj----522 Interval (简单树状数组)
    HDUOJ-----2838Cow Sorting(组合树状数组)
    HDUOJ---2642Stars(二维树状数组)
    HDUOJ -----Color the ball
    ACM遇到的问题与解决方案
    ELK架构下利用Kafka Group实现Logstash的高可用
    Linux给力的Shell命令
    i18n 语言码和对应的语言库
    jar启动脚本shell
    持续集成和部署工具GOCD
  • 原文地址:https://www.cnblogs.com/zjhblogs/p/14338407.html
Copyright © 2020-2023  润新知