php - How to change exception message of Exception object?
533
So I catch an exception (instance of Exception class) and what I want to do is change its exception message.
I can get the exception message like this:
$e->getMessage();
But how to set an exception message? This won't work:
$e->setMessage('hello');
Answer
Solution:
For almost every single case under the sun, you should throw a new Exception with the old Exception attached.
Every once in a while though, you do actually need to manipulate an Exception in place, because throwing another Exception isn't actually what you want to do.
A good example of this is in Behat
FeatureContext
when you want to append additional information in an@AfterStep
method. After a step has failed, you may wish to take a screenshot, and then add a message to the output as to where that screenshot can be seen.So in order to change the message of an Exception where you can just replace it, and you can't throw a new Exception, you can use reflection to brute force the parameters value:
Here's that example the Behat in context:
Again, you should never do this if you can avoid it.
Source: My old boss
Answer
Solution:
Just do this, it works I tested it.
Answer
Solution:
You can't change Exception message.
You can however determine it's class name and code, and throw a new one, of the same class, with same code, but with different message.
Answer
Solution:
You can extend Exception and use the parent::__construct to set your message. This gets around the fact that you cannot override getMessage().
Answer
Solution:
here a generified snippet i'm using.
Answer
Solution:
An ugly hack if you don't know which kind of exception you're handling (that can have its own properties) is to use reflection.
You should use this crap wisely in very specific case when you don't have any other choice.
Answer
Solution:
You can't change the message given by the Exception class. If you wanted a custom message, you would need to check the error code using $e->getCode() and create your own message.
Answer
Solution:
If you really wanted to do this (in the only situation I can think that you might want to do it), you could re-throw the exception:
Answer
Solution:
You can extend Exception with your own, and put a setter in it
Answer
Solution:
The php Exception class has a
__toString()
method which is the only method within the Exception class that is notfinal
, meaning it can be customised.You use it as follows within
try-catch
block:Output would be:
Answer
Solution:
This is an improved version of David Chan's answer. It's a re-throw solution which uses
get_class
to rethrow the same exception type, and it passes all parameters to the constructor, even in the case of, which has six rather than three constructor parameters.