Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change exception message of Exception object?

Tags:

php

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'); 
like image 487
Richard Knop Avatar asked Dec 08 '11 11:12

Richard Knop


People also ask

How do I create a custom exception message?

Steps to create a Custom Exception with an ExampleCreate one local variable message to store the exception message locally in the class object. We are passing a string argument to the constructor of the custom exception object. The constructor set the argument string to the private string message.

How do I return an exception message in C#?

Throw the exception, have a try/catch block in the code that calls your method, and show the message box from the catch block. In fact, don't even have a try/catch block or any return values in your createFolding() method at all.

What is exception message in C#?

The Message property is overridden in classes that require control over message content or format. Application code typically accesses this property when it needs to display information about an exception that has been caught. The error message should be localized.

What does exception message mean?

An exception occurs when a package or shipment encounters an unforeseen event, which could result in a change to the expected delivery day. Examples of exception include: address unknown, damage to shipment, or signature not received.


2 Answers

For almost every single case under the sun, you should throw a new Exception with the old Exception attached.

try {     dodgyCode(); } catch(\Exception $oldException) {     throw new MyException('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

like image 160
DanielM Avatar answered Sep 29 '22 20:09

DanielM


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; 
like image 36
CMCDragonkai Avatar answered Sep 29 '22 19:09

CMCDragonkai