我有一个具有以下路由的 Laravel 4.2 应用程序:
Route::group(['prefix' => 'api/v1'], function()
{
Route::resource('service_logs', 'ServiceLogsController', [
'only' => ['index', 'store', 'show']
]);
});
ServiceLogsController
Controller 从 ApiController
扩展而来,看起来像这样缩减版本:
class ApiController extends \BaseController {
protected $statusCode = 200;
public function getStatusCode()
{
return $this->statusCode;
}
public function setStatusCode($statusCode)
{
$this->statusCode = $statusCode;
return $this;
}
public function respondInternalError($message = 'Internal Error!')
{
return $this->setStatusCode(500)->respondWithError($message);
}
public function respondWithError($message)
{
return Response::json([
'error' => [
'message' => $message,
'status_code' => $this->getStatusCode()
]
], $this->getStatusCode());
}
// ...
}
我想做的是,每当发生未捕获的异常时,我想在我的 ApiController
上调用 respondInternalError()
方法,以便API 使用者有一致的响应,而不是什么都没有或 html whoops
错误。
为此,我尝试在我的 app/start/global.php
App::error(function(Exception $exception, $code)
{
Log::error($exception);
if (Request::is('api/*'))
{
App::make('ApiController')->respondInternalError('Uncaught api exception error occurred - ' . $exception->getMessage());
}
});
为了测试它,我尝试向以下网址发出 POST 请求:/api/v1/service_logs/123。
这是行不通的,因为那个 URL 是一个 GET url,所以 Laravel 会抛出正确的 method not allowed exception
。但是,它没有被捕获。
知道如何在每个 Controller 类基础上实现捕获所有异常处理程序吗?
更新 稍微改进了工作“全局”api 异常处理程序
App::error(function(Exception $exception, $code)
{
Log::error($exception);
if (Request::is('api/*'))
{
$errorName = Symfony\Component\HttpFoundation\Response::$statusTexts[$code];
return App::make('ApiController')
->setStatusCode($code)
->respondWithError($errorName . ' error has occurred.');
}
});
当发生错误时,你现在得到这个(在 Chrome + Postman 中完成测试):
最佳答案
解决方案其实非常非常简单。您只需要返回您的 Controller 函数的返回值
if (Request::is('api/*'))
{
return App::make('ApiController')->respondInternalError('Uncaught api exception error occurred - ' . $exception->getMessage());
}
关于php - Laravel api类异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27566433/