如何让 Laravel 返回 JSON REST API 的自定义错误
问题描述
我正在开发某种 RESTful API.当发生一些错误时,我会抛出一个 App::abort($code, $message)
错误.
I'm developing some kind of RESTful API. When some error occurs, I throw an App::abort($code, $message)
error.
问题是:我希望他抛出一个带有键代码"和消息"的 json 格式的数组,每个都包含上述数据.
The problem is: I want him to throw a json formed array with keys "code" and "message", each one containing the above mentioned data.
有谁知道这是否可行,如果可行,我该怎么做?
Does any one knows if it's possible, and if it is, how I do it?
推荐答案
转到你的 app/start/global.php
.
这会将 401
和 404
的所有错误转换为自定义 json 错误,而不是 Whoops 堆栈跟踪.添加这个:
This will convert all errors for 401
and 404
to a custom json error instead of the Whoops stacktrace. Add this:
这是处理此错误的众多选项之一.
This is one of many options to handle this errors.
制作 API 最好创建自己的帮助程序,例如扩展 Response
类的 Responser::error(400, 'damn')
.
Making an API it is best to create your own helper like Responser::error(400, 'damn')
that extends the Response
class.
有点像:
这篇关于如何让 Laravel 返回 JSON REST API 的自定义错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!