沃梦达 / 编程问答 / php问题 / 正文

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

How can I make Laravel return a custom error for a JSON REST API(如何让 Laravel 返回 JSON REST API 的自定义错误)

本文介绍了如何让 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.

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

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

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

推荐答案

转到你的 app/start/global.php.

这会将 401404 的所有错误转换为自定义 json 错误,而不是 Whoops 堆栈跟踪.添加这个:

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

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.

制作 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.

有点像:

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);
}

这篇关于如何让 Laravel 返回 JSON REST API 的自定义错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何让 Laravel 返回 JSON REST API 的自定义错误

基础教程推荐