I'm trying to show a custom exception message while preserving the inner exception.
Here is my sample code:
public class Class1
{
public Class1()
{
try
{
throw new WebException("Initial Exception");
}
catch (WebException we)
{
throw new myException("Custom Message", we);
}
}
}
public class myException : WebException
{
public myException(string msg, WebException e) : base(msg, e) { }
}
When I run this code it shows me the custom message in the debugger: Screenshot1
yet still sends the innerexception message to the client: Screenshot2
What am I doing wrong here? How do I preserve the inner exception while showing my own custom message?
2 Answers 2
The way to customise the message the user sees is to provide a custom error page.
Comments
I suspect it's because the ApplicationException isn't being effectively handled and the catch block throws an exception which is then being picked up as a base Exception. The debugger is then listing both exceptions.
I think this will give the behaviour you're after (I've written as a console app)
using System;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
myException exception;
try
{
throw new ApplicationException("Initial Exception");
}
catch (ApplicationException e)
{
exception = new myException("Custom Message", e);
}
catch (Exception e)
{
throw e;
}
if (exception != null)
{
throw exception;
}
}
}
}
public class myException : ApplicationException
{
public myException(string msg, ApplicationException e) : base(msg, e) { }
}
throw;rather thanthrow e;as your finalExceptioncatchhandler - it'll preserve the stack information while what you have will not.throw;because I still want to preserve the initial exception