Laravel 5一般错误为JSON [英] Laravel 5 general error as json
问题描述
我只是转到laravel 5,并且在HTML页面中从laravel接收错误.像这样:
Im just move to laravel 5 and im receiving errors from laravel in HTML page. Something like this:
Sorry, the page you are looking for could not be found.
1/1
NotFoundHttpException in Application.php line 756:
Persona no existe
in Application.php line 756
at Application->abort('404', 'Person doesnt exists', array()) in helpers.php line
当我使用laravel 4都可以正常工作时,错误采用json格式,这样我就可以解析错误消息并向用户显示消息. json错误的示例:
When i work with laravel 4 all works fine, the errors are in json format, that way i could parse the error message and show a message to the user. An example of json error:
{"error":{
"type":"Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
"message":"Person doesnt exist",
"file":"C:\\xampp\\htdocs\\backend1\\bootstrap\\compiled.php",
"line":768}}
我如何在laravel 5中实现这一目标.
How can i achieve that in laravel 5.
对不起,我的英语不好,非常感谢.
Sorry for my bad english, thanks a lot.
推荐答案
我早些时候来到这里,是为了寻找如何在Laravel中的任何地方抛出json异常的方法,答案使我走上了正确的道路.对于找到此搜索类似解决方案的任何人,这是我在应用程序范围内实施的方式:
I came here earlier searching for how to throw json exceptions anywhere in Laravel and the answer set me on the correct path. For anyone that finds this searching for a similar solution, here's how I implemented app-wide:
将此代码添加到app/Exceptions/Handler.php
if ($request->ajax() || $request->wantsJson()) {
return new JsonResponse($e->getMessage(), 422);
}
将此添加到用于处理对象的方法中:
Add this to the method to handle objects:
if ($request->ajax() || $request->wantsJson()) {
$message = $e->getMessage();
if (is_object($message)) { $message = $message->toArray(); }
return new JsonResponse($message, 422);
}
然后在您想要的任何地方使用此通用代码:
And then use this generic bit of code anywhere you want:
throw new \Exception("Custom error message", 422);
它将把ajax请求后引发的所有错误转换为Json异常,可以随时使用它:-)
And it will convert all errors thrown after an ajax request to Json exceptions ready to be used any which way you want :-)
这篇关于Laravel 5一般错误为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!