1

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?

Greg
  • 8,574
  • 21
  • 67
  • 109
  • 2
    Notice that it's still showing your custom myException information. I'm guessing this is a "feature" of ASP.NET's server that shows the inner exception data first as the source originator of the problem. I imagine, perhaps, that this is for convenience for server-side debugging. Possibly there's a server config option to control this but I don't know. – Chris Sinclair May 10 '12 at 20:48
  • "You should not define new exception classes derived from ApplicationException; use Exception instead. In addition, you should not write code that catches ApplicationException." - Microsoft – Jesse C. Slicer May 10 '12 at 21:12
  • Also, I think you may be wanting `throw;` rather than `throw e;` as your final `Exception` `catch` handler - it'll preserve the stack information while what you have will not. – Jesse C. Slicer May 10 '12 at 21:18
  • @JesseC.Slicer, I'm just using this code an an example, I didn't have any luck with `throw;` because I still want to preserve the initial exception – Greg May 10 '12 at 21:36

2 Answers2

3

The way to customise the message the user sees is to provide a custom error page.

http://support.microsoft.com/kb/306355

Ben
  • 34,935
  • 6
  • 74
  • 113
0

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) { }
}
joocer
  • 1,111
  • 1
  • 7
  • 11