Laravel例外处理程序
问题描述:
我的工作与Laravel项目,例外越来越逮住在Exceptions\Handler.php
渲染函数里面,像这样:Laravel例外处理程序
public function render($request, Exception $e){
switch(get_class($e)){
case SOME_EXCEPTION::class:
do something..
...
...
default:
do something..
}
,你可以看到它变得丑陋和乱码的问题很多案例
如何解决这个问题?
答
好吧,找到一种方法,使它看起来更好。 如果有人想提高他的例外laravel处理程序遵循这样的:
在应用/供应商创造新的服务提供者,让我们把它叫做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);
}
}
最后一件事要记住的是摆在config/app.php
下的应用程序设置的ServiceProvider
只需添加:
\App\Providers\ExceptionServiceProvider::class
我希望你会像我一样发现这个有用的。
答
如果您的自定义异常扩展了通用接口,您可以只检查该接口,然后调用合同方法。
if ($e instanceof CustomExceptionInterface) {
return $e->contractMethod();
}
删除了模糊或主要基于意见的内容(如**最佳**练习) –