我正在使用Laravel开发一个项目,Exceptions\Handler.php
如下这样在render函数内部捕获了异常:
public function render($request, Exception $e){
switch(get_class($e)){
case SOME_EXCEPTION::class:
do something..
...
...
default:
do something..
}
如您所见,在许多情况下,问题变得越来越丑陋和凌乱
如何解决这个问题?
好的,找到一种使它看起来更好的方法。如果有人想在laravel中改进他的Exceptions处理程序,请遵循以下步骤:
在应用程序/提供程序下,创建新的服务提供程序,将其命名为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()
代码和消息的方法和获取器的类
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
render函数中:
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
希望您会像我一样找到有用的方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句