Best practice for registering custom exceptions in PHP

I have a custom exception (which extends further in other custom exceptions). My project requires a log of all userExceptions (and all its divisions) that occur. I have a log that can log customException (and everything else). One way to do this is to explicitly log an exception when it is handled as follows.

try{
    //some exception occur
}
catch(customeException $e)
{
     $log->logException($e);
     $e->showMessage(); // or do anything that we have to do with the error.
}

Since we are registering all customExceptions, in another way that I can think of, update the customException constructor and register an exception right inside the constructor. Thus, it ensures that all user exceptions are logged. However, if we move on to this path, my questions are:

  • How to insert a registrar into a custom exception?
  • Would it be against the principle of SRP?
  • Will this be considered bad practice in the sense of OOP or what is the best practice in this matter?
+4
source share
1 answer

I think the logger injection in CustomException is wrong because (as you pointed out) this interrupts SRP and increases the complexity of your exception classes.

I suggest you separate Exception from ExceptionHandler. The exception class should contain only information about "what (and where) went wrong." ExceptionHandler is responsible for the exception of registration (and if necessary, does other work with the exception).

, ExceptionHandler ( set_exception_handler set_error_handler - , symfony 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
0

Source: https://habr.com/ru/post/1694262/


All Articles