zoukankan      html  css  js  c++  java
  • 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."
            ]
        }
    }
    
  • 相关阅读:
    int string java 呼转
    E:Encountered a section with no Package: header, E:Problem with MergeList /var/lib/apt/lists/******
    东南大学课程表爬虫
    文件传输器
    springmvc-项目启动初始化类
    分享一段线程队列--生产者和消费者代码
    maven-assembly-plugin 插件打包一个bug手动解决方式
    dubbo Main独立运行,脱离web容器
    Logstash5.6.1-Kafka插件配置
    kafka 设置开机启动
  • 原文地址:https://www.cnblogs.com/zjhblogs/p/14338407.html
Copyright © 2011-2022 走看看