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错误的一个例子:

{"error":{
"type":"Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
"message":"Person doesnt exist",
"file":"C:\\xampp\\htdocs\\backend1\\bootstrap\\compiled.php",
"line":768}}

我怎样才能在拉威尔5中做到这一点.

Sorry for my bad english, thanks a lot.

推荐答案

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:

Add this code to the render method of 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);

And it will convert all errors thrown after an ajax request to Json exceptions ready to be used any which way you want :-)

Laravel相关问答推荐

到查询构建器的MySQL查询

laravel vue 惯性分页器删除上一个和下一个链接

验证判断请求的值是否存在于另一个表 Laravel 9 中

如何在 Laravel 中将 Select 选项表单插入数据库

Laravel/Eloquent:致命错误:在非对象上调用成员函数 connection()

在 laravel 中动态更改时区

.gitignore 不忽略文件夹

使用模型工厂、一对一和一对多关系定义 Laravel 外键,而不创建不必要的模型

如何在 Laravel 5.2 中手动发送密码重置请求?

Laravel db 迁移 - renameColumn 错误 - 请求了未知的数据库类型枚举

扩展模型 == 扩展 Eloquent?

Laravel 验证 pdf mime

Laravel 中的单会话登录

Grammar::parameterize() 必须是数组类型

Laravel 接口

如何卸载 Laravel Passport

laravel如何访问具有表编号名称的列?

Laravel Eloquent 模型属性

如何在特定项目中禁用初始化 JS/TS 语言功能?

如果参数不是整数,如何以不同方式定义路由