laravel 5 在哪里处理 ValidationException?

Where does laravel 5 handle the ValidationException?

If the incoming request was an AJAX request, no redirect will be generated. Instead, an HTTP response with a 422 status code will be returned to the browser containing a JSON representation of the validation errors.

这是行不通的!我正在尝试通过 ajax 请求访问路由,它会重定向回来。

If validation passes, your code will keep executing normally. However, if validation fails, an Illuminate\Contracts\Validation\ValidationException will be thrown. This exception is automatically caught and a redirect is generated to the user's previous location. The validation errors are even automatically flashed to the session!

现在我想知道 laravel 在哪里捕获这个异常以便我可以修改它?

这是在 FormRequest 内部处理的 class:

protected function failedValidation(Validator $validator)
{
    throw new HttpResponseException($this->response(
        $this->formatErrors($validator)
    ));
}

您可以在自己的 Request 对象中覆盖此函数,并以您喜欢的任何方式处理失败的验证。

经过一段时间的研究后,我将 post 我的结果,这样遇到这个问题的任何人都可以节省很多时间。

@Faiz,如果您想坚持 laravel 行为,从技术上讲您不应该改变任何事情(我将始终尝试遵循泰勒的建议)。因此,要接收 422 响应代码状态,您需要告诉 phpunit 您将发送一个 XMLHttpRequest。也就是说,这适用于 laravel 5

        $response = $this->call('POST', $url, [], [], [],
        ['HTTP_X_Requested-With' => 'XMLHttpRequest']);

更多信息请访问 Github Issues. Besides, if you look at Symfony\Component\HttpFoundation\Request@isXmlHttpRequest you will find that this header is used by "common JavaScript frameworks" and refers to this link

还没有在浏览器上测试过,但我想这应该也可以。