If an exception is not written to the exception.log file with the exception model as context, it is not recognized and analyzed correctly in New Relic or other PSR-3 monolog-compatible log storage. Logging only a part of the exception (or logging it to the wrong file) leads to bugs in production when exceptions are overlooked.
Correct exception handling
The following checklist provides examples to demonstrate correct exception handling.
Write to the exception log
Write to the exception log using the following pattern, regardless of further actions, unless there is a compelling reason not to.
This approach automatically saves the $e->getMessage to the log message and the $e object to the context, following the PSR-3 context standard. This is done in \Magento\Framework\Logger\Monolog::addRecord.
Mute signals
Mute signals by not logging exceptions that are part of the intended operations flow. No follow-up action is necessary when the exception is encountered, so it does not need to be logged and analyzed when it occurs. Add a comment indicating the reason for muting signals and that it is intentional. Combine with phpcs:ignore.
The following examples demonstrate incorrect exception handling.
Logic before logging
Logic before logging can lead to another exception or fatal error, which prevents the exception from being logged and should be replaced by correct example.
This approach introduces line breaks in the message, which is not compliant with PSR-3. The exception, including stack trace, must be part of the message context to ensure that it is saved correctly with the message in New Relic or other PSR-3 monolog-compatible log storage.
The exception is downgraded to an error, which does not allow an object to be passed, but only a string, hence the getMessage(). This causes the trace to be lost and should be replaced by the correct examples shown in Write to the exception log or Downgrade exceptions.
Instead of passing the object $e, only $e->getMessage() is passed. This causes the trace to be lost and should be replaced by the correct examples shown Write to the exception log or Downgrade exceptions.
Omitting the phpcs:ignore line triggers a warning in PHPCS and should not pass your CI. This should be replaced by the correct example shown in Mute signals.