Throw Exception, message passed into constructor won't appear in PHP error

大兔子大兔子 提交于 2019-12-11 20:25:05

问题


I have a given class with some methods in it, one of which throws an exception as per the following when certain faulty criteria is met:

PHP

if ($this->mode !== null) {
    throw new LogicException('Nem kezdhető új "insert" utasítás.');
}

If I do not handle this error, PHP will show the "Fatal Error" message as expected, but not the custom message that was passed into the first parameter of the constructor of LogicException:

Fatal error: in /home/uxxxxxxxxx/public_html/test.php on line 87

I expected that throwing an exception outside of a try ... catch block would produce the following output in the browser:

Fatal error: Nem kezdhető új "insert" utasítás. in /home/uxxxxxxxxx/public_html/test.php on line 87

If I specify a custom exception handler, it is possible to to display the original message, albeit in a different style. I know how I could mimic the original behaviour of PHP handling catchable fatal errors, but I do think the message should be displayed without requiring that, purely by throwing a non-caught exception.

Note: swapping LogicException to Exception doesn't change anything.


回答1:


Note: I did not include the key to the solution in my initial question, the original message itself. In the question, I translated the message to english in the hope of better readability, but the original one had UTF-8 characters within.

As it turns out, the problem was that the original message,

Nem kezdhető új "insert" utasítás.

contains UTF-8 characters, which break exception handling if used inside a file without UTF-8 encoding. Switching the file encoding accordingly solved the issue.

The following topic has numerous quality answers which describe the issue: PHP 5.4 throw exception - Can't see message with ISO-8859-1 encoded string message




回答2:


It is possible to you to surround the above call with a try {...} catch block but it will be up to you to declare what behaviour you want for your script.

When caught, an exception is an object that can contain some data (like there with your custom message). You can extract those data according to your will thanks to methods.

If we have a look at http://php.net/manual/fr/class.logicexception.php, we can see that there is a getMessage(...) methods which returns the message you stored.

All you have to do would be :

try {
// the code reaching the one above
}
catch (LogicException $e) {
  echo $e->getMessage();
}

EDIT : But at mentionned above, there must be another error triggered before your custom one since it would not be displaying a "Fatal error"

I hope this helped you, sorry for bad englado :(



来源:https://stackoverflow.com/questions/30174237/throw-exception-message-passed-into-constructor-wont-appear-in-php-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!