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 InnerException
s the exceptionWritingView
could've had.
Is reflection the only way out here? Would it be that horrible to do it with reflection?
You can use System.AggregateException.
Example:
WriteGracefulResponse(new AggregateException(new Exception[]
{
exceptionWritingView,
originalUnhandledException
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With