0

In Magento 1, I was able to trap all exceptions and errors within custom handler functions at the class level in order to reliably perform some final tasks before the script ended.

Has anyone been able to get this to work within Magento 2? Did something change in the way that handlers work in M2?

If I throw an exception to force it, the exception is reported, but the custom functions are not fired. I've confirmed that the handlers are being set properly, and I'm also using the appropriate use \Exception line at the top of my script.

Handlers:

register_shutdown_function(array($this, "customFatalErrorHandler"));
set_exception_handler(array($this, "customExceptionHandler"));
set_error_handler(array($this, "customErrorHandler"));

Functions:

private function customFatalErrorHandler() {

    echo "custom fatal error handler fired\n";

}

private function customExceptionHandler($exception) {

    echo "custom exception handler fired\n";

}

private function customErrorHandler($errno, $errstr, $errfile, $errline, $errcontext) {

    echo "custom error handler fired\n";

}

Trigger:

throw new Exception('My Test Exception');

Output:

[Exception]
My Test Exception

Expected Output (either order):

custom exception handler fired
[Exception]
My Test Exception

OR

[Exception]
My Test Exception
custom exception handler fired
1

Apparently, I've made a mistake. While trying to tighten up security in the switch from M1 to M2, I made the custom error and exception handler functions private. Through additional trial and error and research, I've learned that they always need to be public.

This solved the problem.

public function customFatalErrorHandler() {

    echo "custom fatal error handler fired\n";

}

public function customExceptionHandler($exception) {

    echo "custom exception handler fired\n";

}

public function customErrorHandler($errno, $errstr, $errfile, $errline, $errcontext) {

    echo "custom error handler fired\n";

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.