Skip to content

Unhandled Exception Listener #15

@mostertb

Description

@mostertb

Problem: When a command is being run in the background (such as via cron), there is no indication that the execution we terminated early due to an unhandled exception. Symfony outputs an error to the terminal however, in many cases this output is ignored in favour of log files when executing in such an automated background fashion.

Solution: Add a kernel listener for the console.exception event that attempts to log the exception to a logfile if it was thrown by a command that extends BaseComand (using the command's own logger)

We already have something like this in the internal Afrihost codebase:

 public function onConsoleException(ConsoleExceptionEvent $event)
    {
        // If the command is a subclass of AHCommandBase, try log the exception to the command's log file
        if($event->getCommand() instanceof AHCommandBase){
            try{
                /* @var $command AHCommandBase */
                $command = $event->getCommand();
                $exception = $event->getException();

                $message = 'Uncaught Exception Encountered! Message: '.$exception->getMessage().PHP_EOL.
                    'File: '.$exception->getFile().PHP_EOL.
                    'Line: '.$exception->getLine().PHP_EOL;
                $command->getLogger()->addEmergency($message);
                $command->getLogger()->addInfo('Trace: '.$exception->getTraceAsString());
            } catch(\Exception $e){
                // do nothing if logging throws further exception
            }
        }
    }

This just needs to be incorporated in to the BaseCommandBundle so that:

  • The listener is an opt in feature (so that we are not forcing everyone's kernel to be clogged up with our listener)
  • The log level of the log entry can be defined in config
  • Something is done about making the log entry format more compatible. Not everyone likes to have erroneous newline characters in their log files (this breaks parsing)

The last task is probably a 'nice to have'

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions