Skip to content
Advertisement

PHP: Append to thrown exception message

Take the following function as an example of what I want to do:

public function save() {
    $this->connect('wb');
    try {
        if(!$this->lock())
            throw new Exception("Unable to acquire configuration locks");
        if (!$backup = $this->backup())
            throw new Exception("Failed to create configuration backup");
        try {
            if(!fwrite($this->_pointer, $this->dump("string")));
                throw new Exception("Error occured while writing to configuration");
            $this->unlock();
            $this->disconnect();
        } catch (Exception $e) {
            if(rename ($backup, $this->_file))
                $e .= PHP_EOL."Successfully restored configuration from backup";
            else
                $e .= PHP_EOL."Failed to restore configuration from backup";
            $this->unlock();
            $this->disconnect();
            throw $e;
        }
    } catch (Exception $e) {
        echo PHP_EOL, $e->getMessage();
    }
}

I have nested try() and catch() statements. An exception is thrown from the inner-most and is caught, I then perform some functions and throw another exception. Notice where I write $e .=, I understand this is the incorrect syntax. What I want to do is append the string to the exception’s $e->getMessage().

How would I go about doing this?

Advertisement

Answer

Create you own exception class and create method for appending string to the message.

<?php
class SuperException extends Exception
{
    public function AppendToMessage($msg)
    {
        // $this->message is inherited from Exception class,
        // where it is protected field (member) of the class
        $this->message .= $msg;
    }
}
?>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement