【问题标题】:Custom exception render ignores validation messages自定义异常渲染忽略验证消息
【发布时间】:2019-08-31 15:49:40
【问题描述】:

为异常处理添加自定义视图后,我的验证消息不再返回,只有 - '给定数据未能通过验证。'

我将以下内容添加到 handler.php 并删除了原来的 parent::render($request, $exception);

public function render($request, Exception $exception){

    return response()->view('error', compact('exception'), 500);

}

有没有办法保留我的验证消息并在验证失败时显示错误视图,因为我讨厌看到默认的“哎呀,发生了错误”视图。

【问题讨论】:

    标签: laravel validation exception


    【解决方案1】:

    我让它按预期工作,以保留由我必须添加到我的 App/Exceptions/Handler.php 的 FormRequest 创建的自定义验证消息:

    use Illuminate\Validation\ValidationException;
    
    public function render($request, Exception $exception)
    {
        if($exception instanceof ValidationException) {
            return parent::render($request, $exception);
        }
        else{
            return response()->view('error', compact('exception'), 500);
        }
    }
    

    【讨论】:

      【解决方案2】:

      如果您进一步查看 parent::render() 的代码,您会看到一行:

      return $this->convertValidationExceptionToResponse($e, $request);
      

      这会将函数应用于withInput()withErrors() 等请求。

      所以,你可以试试类似这样的代码:

      public function render(...) {
        return response()->view('error', ...)
       ->withInput(Arr::except($request->input(), $this->dontFlash))
       ->withErrors($exception->errors(), $exception->errorBag);
      }
      

      【讨论】:

        猜你喜欢
        • 2019-06-19
        • 1970-01-01
        • 2012-04-22
        • 2014-06-10
        • 1970-01-01
        • 2012-12-12
        • 1970-01-01
        相关资源
        最近更新 更多