In Global.asax we have a class of type System.Web.HttpApplication named MvcApplication that represents the application and in which we can handle various events.
I'm interested in the Application_Error handler. In this handler we can use all the properties of the class MvcApplication.
-1-
Is always true that '(MvcApplication)sender' and 'this' are the same object?
protected void Application_Error(object sender, EventArgs e)
{
var httpApp = (MvcApplication)sender;
var equality1 = httpApp == this; // always true?
}
-2-
What is the best way to get the error? The following examples return the same error?
Exception ex0 = this.Context.Error;
Exception ex1 = httpContext.Error;
Exception ex2 = Server.GetLastError();
var equality3 = ex1 == ex2; // true?
Global.asax
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Response.Clear();
if (exception != null)
{
Common.WriteErrorLog(exception);
}
HttpException httpException = exception as HttpException;
if (httpException != null)
{
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
switch (httpException.GetHttpCode())
{
case 404:
// page not found
routeData.Values.Add("action", "HttpError404");
break;
case 500:
// server error
routeData.Values.Add("action", "HttpError500");
break;
default:
routeData.Values.Add("action", "Index");
break;
}
routeData.Values.Add("error", exception.Message);
// clear error on server
Server.ClearError();
Response.RedirectToRoute(routeData.Values);
// at this point how to properly pass route data to error controller?
//Response.Redirect(String.Format("~/Error/{0}/?message={1}", "Index", exception.Message));
}
}
Controller :
public class ErrorController : Controller
{
// GET: Error
public ActionResult Index(string error="")
{
ViewBag.Message = error;
return View();
}
public ActionResult HttpError404(string error = "")
{
ViewBag.Message = error;
return View();
}
public ActionResult HttpError500(string error = "")
{
ViewBag.Message = error;
return View();
}
}
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