在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.
我第一次使用自定义PHP异常,希望能够帮助清理一些代码 。 特别是,我正在捕捉PDO错误,并编写了一个类来向自己邮寄错误的堆栈跟踪。 我目前正在做的事情如下: p>
尝试{
// // db stuff
}} catch(PDOException $ e){\ n
抛出新的My_Own_Exception($ e);
退出;
}
code> pre>
我的My_Own_Exception通过以下方式完成工作: p> \ n
类My_Own_Exception扩展Exception
{
/ *代码以邮寄自己错误信息:此部分有效!
}
code> pre>
虽然上述工作正常,但我觉得我应 em>能够写出更清洁的内容,例如: p>
try {
} catch(My_Own_Exception $ e){
exit;
}
code> pre>
其中My_Own_Exception是PDOException类的扩展。 关于这个的一些问题:首先,第二种方法是更好的方法吗? 第二,如果是的话,有可能吗? 第三,如果可能的话,如果My_Own_Exception从未在任何地方实例化,我怎么让PHP知道My_Own_Exception“存在”? 希望第三个问题有道理:我的直觉告诉我,如果我能做到这一点,那么我的方法应该是可行的。 p>
div>
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.