Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the message of a custom Exception without passing it to the base constructor

I want to make a custom Exception in C#, but in theory I do need to do a little parsing first before I can make a human readable ExceptionMessage.

The problem is that the orginal Message can only be set by calling the base constructor of Messsage, so I can't do any parsing in advance.

I tried overring the Message property like this:

public class CustomException : Exception {     string _Message;      public CustomException(dynamic json) : base("Plep")     {         // Some parsing to create a human readable message (simplified)         _Message    = json.message;     }      public override string Message     {         get { return _Message; }     } } 

The problem is that the Visual Studio debugger still shows the message that I've passed into the constructor, Plep in this case.

throw new CustomException( new { message="Show this message" } ) 

results in:

Visual Studio Exception Dialog

If I leave the base constructor empty it will show a very generic message:

An unhandled exception of type 'App.CustomException' occurred in App.exe

Question

It looks like the Exception Dialog reads some field/property that I don't have any access too. Is there any other way to set a human readable error message outside the base constructor on Exception.

Note that I'm using Visual Studio 2012.

like image 543
Dirk Boer Avatar asked Jul 17 '13 09:07

Dirk Boer


People also ask

How do you customize an exception message in Java?

In order to create custom exception, we need to extend Exception class that belongs to java.lang package. Consider the following example, where we create a custom exception named WrongFileNameException: public class WrongFileNameException extends Exception { public WrongFileNameException(String errorMessage) {

How do I create an exception message?

You can only set the message at the creation of the exception. Here is an example if you want to set it after the creation. Show activity on this post. Well, if the API offers an exception that suits your needs (IllegalArgumentException for example), just use it and pass your message in the constructor.

What are the signatures of the constructors that all exceptions should have?

Exception types must implement the following three public constructors: public NewException() public NewException(string) public NewException(string, Exception)


1 Answers

Just put the formatting code into a static method?

public CustomException(dynamic json) : base(HumanReadable(json)) {} private static string HumanReadable(dynamic json) {     return whatever you need to; } 
like image 74
Sebastian Redl Avatar answered Oct 19 '22 21:10

Sebastian Redl