laravel 5 在哪里处理 ValidationException?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28917830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Where does laravel 5 handle the ValidationException?
提问by Faiz Ahmed
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 请求,则不会生成重定向。相反,带有 422 状态代码的 HTTP 响应将返回到浏览器,其中包含验证错误的 JSON 表示。
This is not working! I am trying to access the route via an ajax request and it redirects back.
这是行不通的!我正在尝试通过 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!
如果验证通过,您的代码将继续正常执行。但是,如果验证失败,则会抛出 Illuminate\Contracts\Validation\ValidationException。此异常会被自动捕获并生成重定向到用户之前的位置。验证错误甚至会自动闪烁到会话中!
Now I want to know where does laravel catch this exception so that I can modify it?
现在我想知道laravel在哪里捕获这个异常以便我可以修改它?
采纳答案by Laurence
This is handled inside the FormRequest class:
这是在 FormRequest 类中处理的:
protected function failedValidation(Validator $validator)
{
throw new HttpResponseException($this->response(
$this->formatErrors($validator)
));
}
You can override this function in your own Request object and handle a failed validation any way you like.
您可以在您自己的 Request 对象中覆盖此函数,并以您喜欢的任何方式处理失败的验证。
回答by Alwin Kesler
After been researching for a while I will post my results so anyone with this problem saves a lot of time.
经过一段时间的研究,我将发布我的结果,因此任何遇到此问题的人都可以节省大量时间。
@Faiz, you technically shouldn't change a thing if you want to stick to laravel behavior (I'll always try to follow taylor's recommendations). So, to receive a 422 response code status you need to tell phpunityou will send a XMLHttpRequest. That said, this works on laravel 5
@Faiz,如果你想坚持 Laravel 的行为,从技术上讲你不应该改变任何东西(我会一直尝试遵循 taylor 的建议)。因此,要接收 422 响应代码状态,您需要告诉phpunit您将发送一个XMLHttpRequest。也就是说,这适用于 laravel 5
$response = $this->call('POST', $url, [], [], [],
['HTTP_X_Requested-With' => 'XMLHttpRequest']);
More information at 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
更多信息请访问Github 问题。此外,如果您查看,Symfony\Component\HttpFoundation\Request@isXmlHttpRequest
您会发现此标头被“常用 JavaScript 框架”使用并引用此链接
Haven't tested on the browser yet, but I think this should work too.
还没有在浏览器上测试过,但我认为这也应该有效。