1

I am writing a user-defined PHP exception handler for my application and would like it to handle different kinds of Exceptions in different ways.

For example if the application throws an uncaught PDOException my handler would send me an email but if an uncaught Exception is thrown another action would be performed.

Currently the handler looks like this:

function exception_handler($po_exception) {
    // If this is a PDO Exception send an email.
    example_email_function('There was a database problem', $po_exception->getMessage());

    // If this is any other type of Exception, let the user know something has gone wrong.
    echo "Something went wrong.\n"; 
}
2
  • Don't you afraid to be spammed in case mysql server get down someday? Commented Mar 18, 2014 at 10:03
  • Hi @YourCommonSense, I agree that this would need to be considered. In my case this handler is only for uncaught Exceptions and there are try catch statements around most areas of the application dealing with the database. This includes database connection so these Exceptions would not go through to this exception handler. Thank you for highlighting this though Commented Mar 18, 2014 at 15:20

2 Answers 2

1

http://www.php.net/manual/en/language.operators.type.php

However, I would advise against such a careless behavior.

If you want to monitor if your site is up and running, just use some external service.

For all the occasional errors just monitor the error logs.

Also, don't use getMessage() but $po_exception itself.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the link. That is helpful and provides a solution. I'm not sure why you are referring to the application being up and running or this as a careless solution. I think you may have misunderstood what this is for. This handler is for exceptions thrown by the application but not caught by the application. We do monitor the error logs but this functionality allows for specific actions to be triggered dependent on the Exception type.
0

To confirm, the solution that answers my question was in the link provided by @YourCommonSense: http://www.php.net/manual/en/language.operators.type.php and the resulting code is:

function exception_handler($po_exception) {
    if ($po_exception instanceof PDOException) {
        // If this is a PDO Exception, pass it to the SQL error handler.
        example_email_function('There was a database problem', $po_exception->getMessage());
    }
    else {
        // Do non database Exception handling here.
    }

    // If this is any other type of Exception, let the user know something has gone wrong.
    echo "Something went wrong.\n";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.