radweb/json-exception-formatter

0.2.0 2014-08-15 09:34 UTC

This package is not auto-updated.

Last update: 2024-09-14 14:14:40 UTC


README

Build Status Latest Stable Version License

Laravel JSON 异常格式化器

一个小的 Laravel 包,当需要时可以将异常格式化为 JSON 格式。

默认情况下,在 Laravel 中,当处于调试模式时,抛出异常会根据需要显示一个漂亮的 JSON 响应(例如 AJAX 响应或 Accept: application/javascript 头部)。

然而,一旦你不在调试模式中(即生产环境),则会显示整个 HTML 响应。

使用此包,当你不在调试模式中时,异常将以 JSON 格式输出(但不包含调试信息,如文件名和行号)。

注意 这不会影响 HTML 请求。只有 AJAX/JSON 请求被修改。

安装

radweb/json-exception-formatter 添加到您的 composer.json 文件中。

{
    "require": {
        "radweb/json-exception-formatter": "dev-master"
    }
}

app/config/app.php 中,将服务提供者添加到 providers 数组

array(
    'providers' => array(
        // ...
        'Radweb\JsonExceptionFormatter\JsonExceptionFormatterServiceProvider',
    )
)

自定义格式化器

您可以覆盖默认的 JSON 异常格式化器以使用不同的格式,或在输出中提供更多详细信息。

要覆盖,实现 Radweb\JsonExceptionFormatter\FormatterInterface 接口,并将其绑定到 IoC 容器。这需要您实现两个方法:formatDebug()formatPlain()

示例实现

<?php

use Radweb\JsonExceptionFormatter\FormatterInterface;

class CustomDebugFormatter implements FormatterInterface {

    public function formatDebug(Exception $e)
    {
        return array(
            'theError' => array(
                'message' => $e->getMessage(),
                'detail' => 'In file '.$e->getFile().' on line '.$e->getLine(),
            ),
        );
    }

    public function formatPlain(Exception $e)
    {
        return array(
            'theError' => array(
                'message' => $e->getMessage(),
                // we don't want to display debug details in production
            ),
        );
    }

}

现在我们只需要将其绑定到 IoC 容器中。在您的应用程序的引导代码中的任何位置添加此内容(如果没有其他地方,则 routes.php 将 suffice)

App::bind('Radweb\JsonExceptionFormatter\FormatterInterface', 'CustomDebugFormatter');

预览

普通请求,调试模式 启用

普通请求,调试模式 禁用

JSON 请求,调试模式 启用

JSON 请求,调试模式 禁用