laravel 使用 request 类验证表单,只返回 500错误 The given data was invalid

laravel 使用 request 类验证表单时,不返回具体字段错误信息和错误状态码422,只返回 500错误 The given data was invalid

这是 laravel 没有对 validateException 进行具体处理,而是直接抛出500错误和上面的信息,在后续的处理中使用 getmessage() 已经获取不到错误信息。这类信息只能通过一下方法获取

$e->validator->errors()->first(),
  • 解决方法1
    在 Exception/handler 的render()进行异常渲染,自定义返回的异常
if ($e instanceof ValidationException){
            //request类验证异常时返回具体信息,而不是The given data was invalid 500异常
            //这类异常信息用getMessage()获取不到
            //dd($e->validator->errors()->first());
            return response()->json([
                'message' => $e->validator->errors()->first(),
                'errors' => $e->validator->getMessageBag(),
                'code' => 422,
                'success' => false,
                'exception' => get_class($e),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => collect($e->getTrace())->map(function ($trace) {
                    return Arr::except($trace, ['args']);})
                ], 422);
        }

//扩展:改成统一的返回样式['code'=>422,'msg'=>xxx]

public function render($request, Exception $exception)
{
    //如果客户端预期的是JSON响应,  在API请求未通过Validator验证抛出ValidationException后,使用errors获取本地化的错误信息数组
    //这里来定制返回给客户端的响应.
   public function render( $request, $e ) {

        //捕获表单验证异常,改成统一的返回样式
        if ( $e instanceof ValidationException  && $request->expectsJson()) {
            return response()->json( [ 'code' => 422, 'msg' => $e->errors() ], 422 );
        }

        return parent::render( $request, $e );
    }
    if ($exception instanceof ModelNotFoundException && $request->expectsJson()) {
        //捕获路由模型绑定在数据库中找不到模型后抛出的NotFoundHttpException
        return $this->error(424, 'resource not found.');
    }
 
 
    if ($exception instanceof AuthorizationException) {
        //捕获不符合权限时抛出的 AuthorizationException
        return $this->error(403, "Permission does not exist.");
    }
 
    return parent::render($request, $exception);
}
  • 解决方法2
    使用 dingo/api
    项目引入 dingo/api 后,在 BaseFormRequest 类中继承 dingo 的 formRequest
//use Illuminate\Foundation\Http\FormRequest;
//改成 dingo 的 FormRequest

异常还是自己重新定义一下,方便调试

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。