简体   繁体   中英

Cleaning up code for a custom exception class in PHP

I'm playing around with custom PHP exceptions for the first time, and would like some help with cleaning up some code. In particular, I'm catching PDO errors, and have written a class to mail myself a stack trace of the errors. The way that I'm currently doing things is as follows:

try {

//db stuff

} catch (PDOException $e) {

    throw new My_Own_Exception($e);
        exit;

}   

where my My_Own_Exception does the job with:

class My_Own_Exception extends Exception
{

  /*code to mail myself error info: this part works!
}

While the above works, I feel like I should be able to just write something cleaner such as:

try {

    } catch (My_Own_Exception $e) {
        exit;
    }

where My_Own_Exception is an extension of the PDOException class. A few questions about this: First, is the second way the better approach? Second, if so, is it possible? Third, if it is possible, how do I let PHP know that My_Own_Exception "exists" if My_Own_Exception is never instantiated anywhere? Hopefully the third question makes some sense: my gut tells me that if I can make that happen, then my approach should be possible.

I don't think that an exception is the correct place for logic, it should contain information about the error. A PDOException is useful because you know it originates from your PDO code, if you throw a MyException instead, you need to at least give more (useful) information.

This being set, you should read BiVOC's comment on your original question.

If you have a custom exception handler , you can then differentiate via instanceof .

function exception_handler($exception) {
    if ($exception instanceof PDOException) {
        //mail
    }
    //always log/etc.
}

What you are trying to do wont work, because nothing in the PDO code will throw your exception, unfortunately. So you are going to have to throw it yourself, like you were in the first example.

Also, the exit in the first example will never be hit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM