我正在开发某种RESTful应用程序接口。当发生一些错误时,我抛出一个App::abort($code, $message)
错误。
问题是:我希望他抛出一个带有键"code“和"message”的json格式的数组,每个键都包含上面提到的数据。
Array
(
[code] => 401
[message] => "Invalid User"
)
有没有人知道这是否可能,如果可能,我是如何做到的?
发布于 2014-03-15 04:35:16
您可以将数组传递给返回的JSON响应:
$returnData = array(
'status' => 'error',
'message' => 'An error occurred!'
);
return Response::json($returnData, 500);
发布于 2016-06-24 15:43:51
下面是我使用的(Laravel 5.2):
根据:https://laravel.com/docs/5.2/errors,我们可以为app\Exceptions\Handler.php
中的错误指定一个自定义的呈现函数。我所做的就是把我的渲染函数改成这样:
/**
* Render an exception into an HTTP response.
* Updated to return json for a request that wantsJson
* i.e: specifies
* Accept: application/json
* in its header
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
if ($request->ajax() || $request->wantsJson()) {
return response()->json(
$this->getJsonMessage($e),
$this->getExceptionHTTPStatusCode($e)
);
}
return parent::render($request, $e);
}
protected function getJsonMessage($e){
// You may add in the code, but it's duplication
return [
'status' => 'false',
'message' => $e->getMessage()
];
}
protected function getExceptionHTTPStatusCode($e){
// Not all Exceptions have a http status code
// We will give Error 500 if none found
return method_exists($e, 'getStatusCode') ?
$e->getStatusCode() : 500;
}
在此之后,您需要做的就是确保您的所有API请求都指定了Accept: application/json
头。希望这能有所帮助:)
发布于 2018-03-26 10:40:39
为了返回与内置validate
方法相同类型的响应,我在5.6中使用了以下内容:
response()->json(['errors' => ['email' => ['The email is invalid.']]], 422);
https://stackoverflow.com/questions/22414524
复制相似问题