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

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

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

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

推荐答案

go 你的app/start/global.php.

这会将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 Response class.

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

Json相关问答推荐

JOLT将扁平数组内其他字段的两个值相乘

Vega通孔信号中的动态梯度

如何使用Aeson解码带有Unicode字符的JSON文件?

如何将加权边列表导出到JSON树?

规范化JSON数据

在 python 中循环 JSON 数组

如何对未知/变量键的字典进行编码?

如何将从嵌套 Select 返回的空值转换为空数组?

如何解决名为 null 的map值

错误字符串的长度超过了maxJsonLength属性设置的值

如何在 jQuery 中循环遍历 JSON 数组?

如何判断字符串是否为json格式

JSON RPC - 什么是id?

如何在不解析的情况下在javascript中同步包含JSON数据?

使用绝对或相对路径在 curl 请求中发送 json 文件

PostgreSQL 中的 JSON 模式验证?

字符串格式 JSON 字符串给出 KeyError

将 json 转换为 C# 数组?

通过 JSON 发送 64 位值的公认方式是什么?

有没有一种快速的方法可以在文本编辑器中将 JavaScript 对象转换为有效的 JSON?