laravel中Dingo api如何Custom ExceptionHandler

背景

在近期使用Dingo api处理接口时,发现laravel本身appExceptionsHandler中无法捕获异常。
后来查阅资料发现,Dingo api接管了api请求的异常处理。导致无法自定义错误返回,很是头疼。
最后在dingo的issues找到了处理方法。

方法

创建一个自定义异常处理
继承自Dingo\Api\Exception\Handler,重写handle方法
app/Exceptions/ApiHandler.php

<?php

namespace App\Exceptions;

use Exception;
use Dingo\Api\Exception\Handler as DingoHandler;

class ApiHandler extends DingoHandler
{
public function handle(Exception $exception)
{
if ($exception instanceof \Illuminate\Auth\AuthenticationException) {
return response()->json([‘message’ => ‘Unauthorized’, ‘status_code’ => 401], 401);
}
return parent::handle($exception);
}
}

创建一个服务容器
app/Providers/DingoServiceProvider.php

<?php

namespace App\Providers;

use Dingo\Api\Provider\DingoServiceProvider as DingoServiceProviders;
use App\Exceptions\ApiHandler as ExceptionHandler;

class DingoServiceProvider extends DingoServiceProviders
{

protected function registerExceptionHandler()
{
$this->app->singleton(‘api.exception’, function ($app) {
return new ExceptionHandler($app[‘Illuminate\Contracts\Debug\ExceptionHandler’], $this->config(‘errorFormat’), $this->config(‘debug’));
});
}
}

将服务容器添加到config/app.php中

‘providers’ => [

App\Providers\DingoServiceProvider::class,

];

结语
参考issues链接:https://github.com/dingo/api/… @shanginn 提供的方法会存在接口返回500,且没有任何数据返回。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理