PHP异常自定义消息
我有一个包装 PHP 异常的抽象类:
abstract class MyException extends Exception
{
public function __construct($message, $code = 0, Exception $previous = null)
{
parent::__construct($message, (int) $code, $previous);
}
}
然后我还有其他类,例如:
class UserException extends MyException
{
public function __toString()
{
return parent::getMessage();
}
}
当尝试抛出错误时 throw new UserException('User does not exit');
它不仅显示消息我定义的。它显示:
致命错误:未捕获的用户不存在抛出 \path\ClassTest.php 第 69 行
如何摆脱“致命错误:未捕获...”部分?
多谢。
编辑:
我找到了答案,使用 set_exception_handler() 将覆盖未捕获的异常。并允许提供回调函数
I have an abstract class that wraps PHP exception:
abstract class MyException extends Exception
{
public function __construct($message, $code = 0, Exception $previous = null)
{
parent::__construct($message, (int) $code, $previous);
}
}
Then I have other classes like:
class UserException extends MyException
{
public function __toString()
{
return parent::getMessage();
}
}
When try throw an error doing throw new UserException('User does not exist');
It doesn't only show the message I defined. It shows:
Fatal error: Uncaught User does not exist thrown in
\path\ClassTest.php on line 69
How do I get rid of the "Fatal error: Uncaught..." portion?
Thanks a lot.
EDIT:
I've found the answer, using set_exception_handler()
will override uncaught exceptions. And allow to provide a callback function
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
“致命错误”部分的产生是因为异常被抛出到 try-catch 语句之外,并最终被 php 错误处理程序捕获。未捕获的异常总是致命的。
尝试使用 try-catch 语句包围生成异常的代码,例如:
或者,您可以创建自己的错误处理程序 --> Linky。
但 try-catch 方法是“正确”的方法。
The "fatal error" part is generated because the exception is thrown outside a try-catch statement, and is finally caught by the php error handler. Uncaught exceptions are always fatal.
Try surrounding the code that generates the exception with a try-catch statement like:
Alternately you could make your own error handler --> Linky.
But the try-catch approach is the "correct" way to do it.