laravel中Dingo api如何Custom ExceptionHandler

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

背景

  • 在近期使用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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

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

Java Concurrency in Practice

Java Concurrency in Practice

Brian Goetz、Tim Peierls、Joshua Bloch、Joseph Bowbeer、David Holmes、Doug Lea / Addison-Wesley Professional / 2006-5-19 / USD 59.99

This book covers: Basic concepts of concurrency and thread safety Techniques for building and composing thread-safe classes Using the concurrency building blocks in java.util.concurrent Pe......一起来看看 《Java Concurrency in Practice》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

随机密码生成器
随机密码生成器

多种字符组合密码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换