Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate two exceptions?

I have the following piece of code for handling exceptions in my web application:

application.Response.Clear();
application.Response.Status = Constants.HttpServerError;
application.Response.TrySkipIisCustomErrors = true;

LogApplicationException(application.Response, exception);
try
{
    WriteViewResponse(exception);
}
// now we're in trouble. lets be as graceful as possible.
catch (Exception exceptionWritingView)
{
    // Exception wrapper = ??
    WriteGracefulResponse(exceptionWritingView);
}
finally
{
    application.Server.ClearError();
}

The issue here is that if there's an exception while attempting to render the response as a ViewResult, I'm "suppressing" the original exception (in the View anyways), and just displaying what caused the error ViewResult to throw.

I'd like taking both exception and exceptionWritingView and make one exception with both, with exceptionWritingView at the top.

This would be:

exceptionWritingView
    -> inner exceptions of exceptionWritingView
            -> original exception that raised the unhandled exception handler
                       -> its inner exceptions

But I can't set the InnerException property on my exception object. So how could I achieve this?

At "best" I could create a new Exception using new Exception(exceptionWritingView.Message, exception), but I'd be losing parts of the StackTrace plus I'd be losing any InnerExceptions the exceptionWritingView could've had.

Is reflection the only way out here? Would it be that horrible to do it with reflection?

like image 598
bevacqua Avatar asked Aug 12 '12 03:08

bevacqua


1 Answers

You can use System.AggregateException.

Example:

WriteGracefulResponse(new AggregateException(new Exception[]
{
    exceptionWritingView,
    originalUnhandledException
}));
like image 180
Steven Avatar answered Oct 31 '22 10:10

Steven