Laravel异常处理程序

时间:2016-07-25 07:33:06

标签: php laravel exception-handling laravel-5.1

我正在使用Laravel开发一个项目,异常会在渲染函数内的Exceptions\Handler.php中被捕获,如下所示:

public function render($request, Exception $e){
      switch(get_class($e)){
              case SOME_EXCEPTION::class:
                    do something..
              ...
              ...
              default:
                    do something..
     }

问题,因为你可以看到很多案件的代码变得丑陋和混乱

如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

如果您的自定义异常扩展了一个公共接口,您可以检查该接口,然后调用契约方法。

if ($e instanceof CustomExceptionInterface) {
    return $e->contractMethod();
}

答案 1 :(得分:0)

好的,找到了让它看起来更好的方法。 如果有人想在laravel中改进他的Exceptions处理程序,请按照以下步骤操作:

在app / providers下创建新的服务提供者,我们称之为ExceptionServiceProvider.php

    class ExceptionServiceProvider extends ServiceProvider {

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(ExceptionFactory::class);
    }

    public function boot(ExceptionFactory $factory){
        $factory->addException(UnauthorizedException::class, JsonResponse::HTTP_NOT_ACCEPTABLE);
        $factory->addException(ConditionException::class, JsonResponse::HTTP_NOT_ACCEPTABLE, "Some Fixed Error Message");

    }
}

在项目的某个位置创建包含ExceptionFactory方法的addException()类以及代码和消息的getter

class ExceptionFactory{


private $exceptionsMap = [];
private $selectedException;

public function addException($exception, $code, $customMessage = null) {
    $this->exceptionsMap[$exception] = [$code, $customMessage];
}

public function getException($exception){
    if(isset($this->exceptionsMap[$exception])){
        return $this->exceptionsMap[$exception];
    }
    return null;
}

public function setException($exception){
    $this->selectedException = $exception;
}

public function getCode(){
    return $this->selectedException[0];
}

public function getCustomMessage(){
    return $this->selectedException[1];
}

}

然后剩下要做的就是在Exceptions/handler.php内 在渲染函数中:

private $exceptionFactory;

    public function __construct(LoggerInterface $log, ExceptionFactory $exceptionFactory){
        parent::__construct($log);
        $this->exceptionFactory = $exceptionFactory;
    }

public function render($request, Exception $e){
        $error = new \stdClass();
        $customException = $this->exceptionFactory->getException(get_class($e));

        if(isset($customException)){
            $this->exceptionFactory->setException($customException);
            $error->code = $this->exceptionFactory->getCode();
            $error->message = $e->getMessage();
            $customMessage = $this->exceptionFactory->getCustomMessage();
            if(isset($customMessage)){
                $error->message = $customMessage;
            }
       }
       return new JsonResponse($error, $error->code);
 }
}

最后要记住的是将ServiceProvider放在config/app.php下的应用设置中,只需添加:

\App\Providers\ExceptionServiceProvider::class

我希望你能像我一样发现它很有用。