32

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');
3
  • 1
    Changing an exception's message (almost always) doesn't make sense. Why do you want to do this?
    – Corbin
    Dec 8, 2011 at 11:36
  • @Corbin Well, I am working on maintaining an old legacy system. I need to solve a certain bug without changing large amounts of code because it would require huge amount of new testing for which there is no time. Basically changing an exception message is the least messy and intrusive way to fix the bug (very ugly but functional which is what matters the most right now). Dec 8, 2011 at 13:50
  • 4
    To those that answered throw a new exception, you lose the stack trace with the original exception. So in the case where an exception is caught in your code, thrown from library code, you may need to massage the original exception, so other layers can interpret it correctly, while leaving the stack trace intact. Jun 25, 2015 at 14:24

11 Answers 11

36

For almost every single case under the sun, you should throw a new Exception with the old Exception attached. There is no need to complicate things.

try {
    dodgyCode();
}
catch(\Exception $oldException) {
    throw new \Exception('My extra information', 0, $oldException);
}

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:

$message = " - My appended message";

$reflectionObject = new \ReflectionObject($exception);
$reflectionObjectProp = $reflectionObject->getProperty('message');
$reflectionObjectProp->setAccessible(true);
$reflectionObjectProp->setValue($exception, $exception->getMessage() . $message);

Here's that example the Behat in context:

    /**
     * Save screen shot on failure
     * @AfterStep
     * @param AfterStepScope $scope
     */
    public function saveScreenShot(AfterStepScope $scope) {
        if (!$scope->getTestResult()->isPassed()) {
            try {
                $screenshot = $this->getSession()->getScreenshot();
                if($screenshot) {
                    $filename = $this->makeFilenameSafe(
                        date('YmdHis')."_{$scope->getStep()->getText()}"
                    );
                    $filename = "{$filename}.png";
                    $this->saveReport(
                        $filename,
                        $screenshot
                    );
                    $result = $scope->getTestResult();
                    if($result instanceof ExceptionResult && $result->hasException()) {
                        $exception = $result->getException();

                        $message = "\nScreenshot saved to {$this->getReportLocation($filename)}";

                        $reflectionObject = new \ReflectionObject($exception);
                        $reflectionObjectProp = $reflectionObject->getProperty('message');
                        $reflectionObjectProp->setAccessible(true);
                        $reflectionObjectProp->setValue($exception, $exception->getMessage() . $message);
                    }
                }
            }
            catch(UnsupportedDriverActionException $e) {
                // Overly specific catch
                // Do nothing
            }
        }
    }

Again, you should never do this if you can avoid it.

Source: My old boss

4
  • 3
    This should be the accepted answer, this is far more useful and expected
    – newms87
    Jan 24, 2018 at 19:24
  • 1
    Thank you, that's nice to hear @newms87. To be fair to the person who accepted the other answer though, my answer was years too late. ;)
    – DanielM
    Jan 25, 2018 at 9:52
  • Can you please be more specific, what is exactly the change? if I just use the try catch it says MyException not found. can you please provide step by step solution? should I create a new class?
    – Bastian
    Mar 1, 2022 at 13:08
  • MyException is just a stand-in for an appropriate exception you have created. For more information on creating Exceptions see this manual entry.
    – DanielM
    Mar 2, 2022 at 15:02
29

Just do this, it works I tested it.

<?php

class Exception2 extends Exception{

    public function setMessage($message){
        $this->message = $message;
    }
    
}

$error = new Exception2('blah');

$error->setMessage('changed');

throw $error;
4
  • 4
    +1. I would name it something other than "Error" to avoid confusion, but I'm assuming this is just for the sake of example. Sep 3, 2014 at 18:19
  • There's no native Error class in PHP, so one could create their own error handling setup. Sep 4, 2014 at 3:03
  • 8
    Error was always a reserved word, and there is now an Error Class (the later is something that didn't exist when @CMCDragonkai made their comment in 2014, though the former was still true).
    – DanielM
    Apr 26, 2016 at 9:46
  • This approach requires that you are also in control of the code throwing the exception, which may not be the case.
    – Jake
    Nov 21, 2019 at 6:29
7

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.

1
  • 7
    Of course exception message can be overridden. This answer shouldn't be accepted.
    – Fahmi
    Jan 3, 2017 at 18:20
7

You can extend Exception and use the parent::__construct to set your message. This gets around the fact that you cannot override getMessage().

class MyException extends Exception {
    function __construct() {
        parent::__construct("something failed or malfunctioned.");
    }
}
2
  • This fails to address the OP's problem. They want to change the message of an existing Exception, not create a new one with a hard-coded message.
    – CJ Dennis
    Jul 8, 2017 at 0:58
  • 1
    You can't change Exception's message. The OP acknowledged this by accepting the answer that said this. Jan 25, 2018 at 23:39
6

here a generified snippet i'm using.

    foreach ($loop as $key => $value) 
    {
        // foo($value);
        thow new Special_Exception('error found')
    }
    catch (Exception $e)
    {
        $exception_type = get_class($e);
        throw new $exception_type("error in $key :: " . $e->getMessage());
    }
1
  • This is the cleanest and most universal response, especially when you want to preserve the exception type without having to resort to reflection.
    – afeique
    Aug 16, 2019 at 20:25
4

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.

    try {
        // business code
    } catch (\Exception $exception) {
        $reflectedObject = new \ReflectionClass(get_class($exception));
        $property = $reflectedObject->getProperty('message');
        $property->setAccessible(true);
        $property->setValue($exception, "new message");
        $property->setAccessible(false);
        throw $exception;
    }

You should use this crap wisely in very specific case when you don't have any other choice.

2
  • Can you explain why you call this solution an ”ugly“ hack? Is using ReflectionClass a bad practice? Your solution seems to be much cleaner to me than all the other anwsers, since it covers all possible Exception subclass constructor parameters.
    – myrdd
    Sep 21, 2018 at 7:34
  • 1
    Yes indeed, if you need to change properties of private attributes, it means you have serious architecture design issues. Consider refactoring before using this solution (ex: throw the right exception with the right properties from the point where it is thrown, or catch all expected exceptions in their own blocks...). Of course if you need to apply some generic logic to handle the universe, this solution could be valid though. You can even catch \Throwable instead of \Exception to be even more generic.
    – Alain
    Sep 24, 2018 at 7:29
1

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.

1

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:

function throwException() {
    throw new Exception( 'Original' );
}

function rethrowException() {
    try {
        throwException();
    } catch( Exception $e ) {
        throw new Exception( 'Rethrow - ' . $e->getMessage() );
    }
}

try {
    rethrowException();
} catch( Exception $e ) {
    echo $e->getMessage();
}
1
  • 4
    the problem with rethrowing like that is that you lose the stack trace Apr 22, 2016 at 11:58
1

The php Exception class has a __toString() method which is the only method within the Exception class that is not final, meaning it can be customised.

class HelloMessage extends Exception {
    function __toString() {
        return $this->getMessage()." you have an error with code: ".$this->getCode();
    }
}

You use it as follows within try-catch block:

try {
    if (2 > 0) {
        throw new HelloMessage("Hello", 10);
    }
} catch (HelloMessage $e) {
    echo $e;
}

Output would be:

Hello you have an error with code: 10
0

You can extend Exception with your own, and put a setter in it

class MyException extends Exception
{
  private $myMessage = '';
  public function getMessage()
  {
    if ($this->myMessage === '') {
    return parent::getMessage();
  } else {
    return $this->myMessage;
  }

  public function setMessage($msg)
  {
    $this->myMessage = $msg;
  }
}
1
  • 6
    Unfortunately for some reason getMessage() is declared as final in PHP and the above code wouldn't work.
    – romaninsh
    Apr 3, 2013 at 14:18
-1

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 ErrorException, which has six rather than three constructor parameters.

foreach ($loopvar as $key => $value) 
{
    doSomethingThatMightThrow($value);
}
catch (\Exception $e)
{
    $exception_type = get_class($e);
    $new_message = "[key '" . $key . "'] " . $e->getMessage();
    if ($e instanceof \ErrorException) {
        throw new $exception_type($new_message, $e->getCode(), $e->getSeverity(), $e->getFile(), $e->getLine(), $e);
    }
    throw new $exception_type($new_message, $e->getCode(), $e);
}
1
  • to downvoters: please point out what's the problem with this answer
    – myrdd
    Dec 16, 2018 at 12:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.