FormRequest验证失败返回500错误而不是422错误(5.2升级后) [英] FormRequest failed validation returns 500 error instead of 422 with errors (after 5.2 upgrade)

查看:50
本文介绍了FormRequest验证失败返回500错误而不是422错误(5.2升级后)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从L5.1更新到L5.2后,我不再收到JSON对象作为对失败的FormRequest的响应(即对AJAX发布请求的响应).

After updating from L5.1 to L5.2, I no longer receive a JSON object as response on a failed FormRequest (i.e. on an AJAX post request).

通常,我会收到422这样的响应:

Usually I would receive a 422 response like:

[
    email: 'E-mail is invalid',
    firstname: 'Firstname must be at least 2 characters'
]

但是现在我收到500错误页面:

But now I receive a 500 error page:

我确保我的AJAX调用将application/json作为Accept标头.

I have ensured that my AJAX calls have application/json as Accept header.

不,我没有手动捕获此异常.我正在使用Laravel提供的默认FormRequest.如文档中所述:在AJAX请求期间使用validate方法时,Laravel将不会生成重定向响应.相反,Laravel会生成一个包含所有验证错误的JSON响应.该JSON响应将以422 HTTP状态代码发送.

And no, I am not manually catching this exception. I am using the default FormRequest that Laravel provides. As they state in documentation: When using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.

例如:php artisan make:request StoreBlogPostRequest( https://laravel.com/docs /5.1/validation#form-request-validation )

推荐答案

@Mattias!

@Mattias!

我最近遇到了同样的问题,我浪费了两个多小时试图了解实际上是什么导致了此问题.由于FormValidator抛出ValidationException(并且未处理),因此在.env文件中禁用调试会导致表单验证显示为500.该问题的解决方案是: 打开 app \ Exceptions \ Handler.php

I've recently had the same issue and I wasted more than 2 hours trying to understand what actually causes this problem. Disabling debugging in .env file causes form validation to display 500 since the FormValidator throws ValidationException (and it is unhandled). The solution for this issue was: Open app\Exceptions\Handler.php

private function handleExceptions($e)
    {
       // Add anywhere in this method the following code
       // It does what the FormValidator does.

        if($e instanceof ValidationException) {

            return redirect()->back()->withErrors($e->validator->getMessageBag()->toArray());
        }

        return response()->view('errors.500', [], 500);
    }

这篇关于FormRequest验证失败返回500错误而不是422错误(5.2升级后)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆