user3953989
user3953989

Reputation: 1929

throw new Exception not getting caught with Server.GetLastError()

In my controller action I'm catching an exception and adding some additional info before bubbling up to the Application_Error() method

ActionResult Index()
{
    try
    {
        var i = 1 / 0;
    }
    catch(Exception e)
    {
        throw new Exception("My new Exception!", e)
    }
}


private void Application_Error(object sender, EventArgs e)
{
    // Breakpoint shows original error! Not my newly thrown one!
    var exception = Server.GetLastError().GetBaseException();
}

Upvotes: 2

Views: 631

Answers (2)

CodingYoshi
CodingYoshi

Reputation: 27009

You do not need to call GetBaseException because that will give you the original exception. Just do this:

var ex = Server.GetLastError();
var inner = ex.InnerException;

Here is a quick test to see what GetBaseException does:

var ex = new Exception("1st");
var ex2 = new Exception("2nd", ex);
var ex3 = new Exception("3rd", ex2);

var exFinal = ex3.GetBaseException();

Console.WriteLine(exFinal.Message);

Output: 1st

Upvotes: 1

spender
spender

Reputation: 120450

A quick trip to the documentation of the Exception.GetBaseException Method clears everything up:

A chain of exceptions consists of a set of exceptions such that each exception in the chain was thrown as a direct result of the exception referenced in its InnerException property. For a given chain, there can be exactly one exception that is the root cause of all other exceptions in the chain. This exception is called the base exception and its InnerException property always contains a null reference.

You set the original Exception as the InnerException of the thrown Exception, therefore the original Exception is the "base exception".

Maybe you shouldn't call GetBaseException if you want to see the most recent Exception in the chain?

Upvotes: 5

Related Questions