Laravel api类异常处理

时间:2014-12-19 12:41:49

标签: php laravel laravel-4 exception-handling

我有一个Laravel 4.2应用程序,其路径如下:

Route::group(['prefix' => 'api/v1'], function()
{
    Route::resource('service_logs', 'ServiceLogsController', [
        'only' => ['index', 'store', 'show']
    ]);
});

ServiceLogsController控制器从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());
    }

    // ...

}

我想做的是,当发生未捕获的异常时,我想在我的respondInternalError()上调用ApiController方法,以便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。但是,它没有被抓住。

知道如何根据控制器类实现catch all all exception?


更新 工作略有改善"全球" 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中进行测试):

enter image description here

1 个答案:

答案 0 :(得分:1)

解决方案实际上非常简单。您只需返回控制器功能的返回值

if (Request::is('api/*'))
{
    return App::make('ApiController')->respondInternalError('Uncaught api exception error occurred - ' . $exception->getMessage());
}