如何将错误异常存储在变量中并将 return 存储为 json
How to store error exception in a variable and return as json
我正在使用 Android 开发使用的 API。
我的框架:Laravel 4.2
和 PHP:PHP5.6
我已经找到了一个库,但无法使用它:https://github.com/Radweb/JSON-Exception-Formatter
我的问题,我有这个错误异常(附图)
我无法在 Mobile 中正确看到它,它只是崩溃了。我正在使用 https://www.getpostman.com/ 来测试我的 API。
我想做的是 return 这个错误异常作为 json 以便 android 可以捕获它。
{
"status" : "fail",
"messsage" : "syntax error, unexpected 's'(T_STRING), expecting ']'",
"file" : "/app/controller/v1/UserController.php",
"line" : "31"
}
要使 Laravel 4 输出异常为 JSON,可以简单地编辑 global.php,如本文所述:http://fideloper.com/error-handling-with-content-negotiation
所以在你的 app/start/global.php 中做这样的事情:
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
App::error(function(HttpExceptionInterface $exception, $code)
{
if ( Request::header('accept') === 'application/json' )
{
return Response::json([
'error' => true,
'message' => $exception->getMessage(),
'code' => $code],
$code
);
}
});
我正在使用 Android 开发使用的 API。
我的框架:Laravel 4.2
和 PHP:PHP5.6
我已经找到了一个库,但无法使用它:https://github.com/Radweb/JSON-Exception-Formatter
我的问题,我有这个错误异常(附图)
我无法在 Mobile 中正确看到它,它只是崩溃了。我正在使用 https://www.getpostman.com/ 来测试我的 API。
我想做的是 return 这个错误异常作为 json 以便 android 可以捕获它。
{
"status" : "fail",
"messsage" : "syntax error, unexpected 's'(T_STRING), expecting ']'",
"file" : "/app/controller/v1/UserController.php",
"line" : "31"
}
要使 Laravel 4 输出异常为 JSON,可以简单地编辑 global.php,如本文所述:http://fideloper.com/error-handling-with-content-negotiation
所以在你的 app/start/global.php 中做这样的事情:
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
App::error(function(HttpExceptionInterface $exception, $code)
{
if ( Request::header('accept') === 'application/json' )
{
return Response::json([
'error' => true,
'message' => $exception->getMessage(),
'code' => $code],
$code
);
}
});