首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使Laravel返回JSON REST API的自定义错误

如何使Laravel返回JSON REST API的自定义错误
EN

Stack Overflow用户
提问于 2014-03-15 03:53:37
回答 5查看 110.8K关注 0票数 38

我正在开发某种RESTful应用程序接口。当发生一些错误时,我抛出一个App::abort($code, $message)错误。

问题是:我希望他抛出一个带有键"code“和"message”的json格式的数组,每个键都包含上面提到的数据。

Array
(
    [code] => 401
    [message] => "Invalid User"
)

有没有人知道这是否可能,如果可能,我是如何做到的?

EN

回答 5

Stack Overflow用户

发布于 2014-03-15 04:35:16

您可以将数组传递给返回的JSON响应:

$returnData = array(
    'status' => 'error',
    'message' => 'An error occurred!'
);
return Response::json($returnData, 500);
票数 37
EN

Stack Overflow用户

发布于 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头。希望这能有所帮助:)

票数 20
EN

Stack Overflow用户

发布于 2018-03-26 10:40:39

为了返回与内置validate方法相同类型的响应,我在5.6中使用了以下内容:

response()->json(['errors' => ['email' => ['The email is invalid.']]], 422);

票数 17
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22414524

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档