问题
I'm developing ASP.Net application and I'm currently struggling with exception handling. I've already managed to do proper exception handling but I don't really know how to handle internal errors that are not suitable for UI.
void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
LogManager.GetCurrentClassLogger().Error(ex);
Response.Clear();
HttpException httpEx = ex as HttpException;
if (httpEx == null)
{
switch(ex.GetType())
{
//Convert ex into httpexception
//with statuscode that depends on the exception type
}
}
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action", "Handler");
routeData.Values.Add("exception", httpEx);
Server.ClearError();
Response.TrySkipIisCustomErrors = true;
var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
var c = ControllerBuilder.Current.GetControllerFactory().CreateController(rc, "Error");
c.Execute(rc);
}
回答1:
Instead of trying to cast your exception to a HttpException just try to create a new HttpException with the original exception as the inner one:
HttpException httpEx = new HttpException(500, msg, ex);
来源:https://stackoverflow.com/questions/45615302/convert-base-exception-into-httpexception