PHP中日志自定义异常的最佳实践
我有一个自定义异常(可能会在其他自定义异常中进一步扩展).我的项目需要记录发生的所有customExceptions(及其所有后代).我有一个记录器,可以记录customException(和其他任何东西).其中一种方法是在处理异常时显式记录异常,如下所示.
try{ //some exception occur } catch(customeException $e) { $log->logException($e); $e->showMessage(); // or do anything that we have to do with the error. } 因为我们记录了所有的customExceptions,我能想到的另一种方式是,更新customException构造函数并在构造函数中记录异常.这样,它确保记录所有customException.但是,如果我们走这条道路,我的问题是: >如何将记录器注入customException? 解决方法
我认为将记录器注入CustomException是不对的,因为(正如你所指出的那样)它会破坏SRP并增加异常类的复杂性.
我建议你将Exception与ExceptionHandler分开.异常类应该只包含“什么(和哪里)出错”的信息. ExceptionHandler负责记录异常(如果需要,还可以执行其他一些异常工作). 因此,您可以设置一个全局ExceptionHandler(使用set_exception_handler和set_error_handler或一些基于框架的异常处理机制,如symfony’s ExceptionListener),它将捕获所有未处理的异常. <?php class ExceptionHandler { /** * @var Logger */ private $logger; public function __construct(Logger $logger) { $this->logger = $logger; } public function handle(Throwable $e) { $this->logger->logException($e); } } 在应用程序代码中,您仍然可以抛出并捕获异常.我认为有4种常见情况. 完全可恢复的例外情况 这是处理可恢复异常的一般方法 – 这种情况当您根本不想失败时,但是当发生此类异常时您需要执行某些操作. <?php try { $methodThatThrowsException(); } catch (DoesNotMatterException $e) { // do some stuff and continue the execution // note,that this exception won't be logged } 可恢复的记录异常 与以前相同,但您要记录此异常. <?php try { $methodThatThrowsException(); } catch (NonCriticalExceptionThatShouldBeLogged $e) { $this->exceptionHandler->handle($e); // log exception // do some stuff and continue the execution } 带有“终结??器”的不可恢复的异常 您想要执行某些特定的业务逻辑然后失败.您可以捕获异常,处理它然后再次抛出它.全局异常处理程序将处理此异常并将其记录下来. <?php try { $methodThatThrowsException(); } catch (CriticalException $e) { // do some stuff like cleanup/transaction rollback throw $e; } 不可恢复的例外情况 如果您只想记录异常并失败,您可以抛出此异常,全局异常处理程序将捕获并记录它. <?php $methodThatThrowsException(); // ExceptionHandler::handle will be executed (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |