php 如何让 Laravel 为 JSON REST API 返回自定义错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22414524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:55:20  来源:igfitidea点击:

How can I make Laravel return a custom error for a JSON REST API

phpjsonrestlaravel-4restful-architecture

提问by Dennis Braga

I'm developing some kind of RESTful API. When some error occurs, I throw an App::abort($code, $message)error.

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

The problem is: I want him to throw a json formed array with keys "code" and "message", each one containing the above mentioned data.

问题是:我希望他抛出一个带有键“代码”和“消息”的 json 格式数组,每个数组都包含上述数据。

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

Does any one knows if it's possible, and if it is, how I do it?

有谁知道这是否可能,如果可能,我该怎么做?

回答by majidarif

go to your app/start/global.php.

去你的app/start/global.php

This will convert all errors for 401and 404to a custom json error instead of the Whoops stacktrace. Add this:

这将转换所有的错误的401404一个自定义的JSON错误,而不是哎呦堆栈跟踪。添加这个:

App::error(function(Exception $exception, $code)
{
    Log::error($exception);

    $message = $exception->getMessage();

    // switch statements provided in case you need to add
    // additional logic for specific error code.
    switch ($code) {
        case 401:
            return Response::json(array(
                    'code'      =>  401,
                    'message'   =>  $message
                ), 401);
        case 404:
            $message            = (!$message ? $message = 'the requested resource was not found' : $message);
            return Response::json(array(
                    'code'      =>  404,
                    'message'   =>  $message
                ), 404);        
    }

});

This is one of many options to handle this errors.

这是处理此错误的众多选项之一。



Making an API it is best to create your own helper like Responser::error(400, 'damn')that extends the Responseclass.

制作 API 最好创建自己的助手,就像Responser::error(400, 'damn')扩展Response类一样。

Somewhat like:

有点像:

public static function error($code = 400, $message = null)
{
    // check if $message is object and transforms it into an array
    if (is_object($message)) { $message = $message->toArray(); }

    switch ($code) {
        default:
            $code_message = 'error_occured';
            break;
    }

    $data = array(
            'code'      => $code,
            'message'   => $code_message,
            'data'      => $message
        );

    // return an error
    return Response::json($data, $code);
}

回答by Philip

You can pass an array to the returned JSON response:

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

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

回答by Ibrahim Lawal

Here is what I use (Laravel 5.2):

这是我使用的(Laravel 5.2):

According to: https://laravel.com/docs/5.2/errors, we can specify a custom render function for errors in app\Exceptions\Handler.php. All I did was to change my render function to this:

根据: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;
    }

After this, all you need do is make sure all your API requests specify the Accept: application/jsonheader. Hope this helps :)

在此之后,您需要做的就是确保您的所有 API 请求都指定了Accept: application/json标头。希望这可以帮助 :)

回答by kjdion84

Heres what I used in 5.6 in order to return the same type of response as the built-in validatemethod:

这是我在 5.6 中使用的,以便返回与内置validate方法相同类型的响应:

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

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

回答by Eliya Cohen

According to Ibrahim's answer, not every ajax request wants JSON, Responding the "status code" andthe "status" is unnecessary since they both mean the same thing. More than that, there's no need to mention in the response "status" at all, since the response code "says" that. Something like that should work perfectly:

根据 Ibrahim 的回答,并非每个 ajax 请求都需要 JSON,响应“状态代码”“状态”是不必要的,因为它们的含义相同。更重要的是,根本不需要在响应中提及“状态”,因为响应代码“说明”了这一点。像这样的东西应该可以完美运行:

/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $e
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $e)
{
    if ($request->wantsJson())
        return response()->json(
            ['message' => $e->getMessage()],
            method_exists($e, 'getStatusCode') ? $e->getStatusCode() : 500);

    return parent::render($request, $e);
}

回答by Sapnesh Naik

Laravel 6:

拉维尔6:

You simply have to set Accept:application/jsonheader in your API request from client-side and Laravel will automatically return a JSON format error.

您只需Accept:application/json在客户端的 API 请求中设置标头,Laravel 将自动返回 JSON 格式错误。

Example:

例子:

{

"message": "Unauthenticated."

}

{

"message": "Unauthenticated."

}

回答by Sheng.Zh

In Laravel5.6, I usually specify a custom render function for errors in app\Exceptions\Handler.php. All I did was to change my render function to this:

在 Laravel5.6 中,我通常会为app\Exceptions\Handler.php. 我所做的就是将渲染函数更改为:

/**
 * Render an exception into an HTTP response.
 *
 * @param \Illuminate\Http\Request $request
 * @param \Exception               $e
 *
 * @return Response
 */
public function render($request, Exception $e)
{
    if ($request->wantsJson() && !($e instanceof ValidationException)) {
        $response = [
            'message' => (string)$e->getMessage(),
            'status_code' => 400,
        ];

        if ($e instanceof HttpException) {
            $response['message'] = Response::$statusTexts[$e->getStatusCode()];
            $response['status_code'] = $e->getStatusCode();
        } else if ($e instanceof ModelNotFoundException) {
            $response['message'] = Response::$statusTexts[Response::HTTP_NOT_FOUND];
            $response['status_code'] = Response::HTTP_NOT_FOUND;
        }

        if ($this->isDebugMode()) {
            $response['debug'] = [
                'exception' => get_class($e),
                'trace' => $e->getTrace()
            ];
        }

        return response()->json([
            'status'      => 'failed',
            'status_code' => $response['status_code'],
            'massage'     => $response['message'],
        ], $response['status_code']);
    }

    return parent::render($request, $e);
}