laravel中Dingo api如何Custom ExceptionHandler

栏目: PHP · 发布时间: 6年前

背景

  • 在近期使用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,
    ...
    ];

结语


以上所述就是小编给大家介绍的《laravel中Dingo api如何Custom ExceptionHandler》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Definitive Guide to MongoDB

The Definitive Guide to MongoDB

Peter Membrey、Wouter Thielen / Apress / 2010-08-26 / USD 44.99

MongoDB, a cross-platform NoSQL database, is the fastest-growing new database in the world. MongoDB provides a rich document orientated structure with dynamic queries that you’ll recognize from RDMBS ......一起来看看 《The Definitive Guide to MongoDB》 这本书的介绍吧!

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具