public class ErrorController : Controller
{
public ActionResult Index(int status, Exception error)
{
Response.StatusCode = status;
ViewBag.status = status;
return View(status);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
}
protected void Application_Error(object sender, EventArgs e)
{
var ex = Server.GetLastError().GetBaseException();
Server.ClearError();
var routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action", "Index");
if (ex.GetType() == typeof(HttpException))
{
var httpException = (HttpException)ex;
var code = httpException.GetHttpCode();
routeData.Values.Add("status", code);
}
else
{
routeData.Values.Add("status", 500);
}
routeData.Values.Add("error", ex);
IController errorController = new trialerror.Controllers.ErrorController();
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}
protected void Application_EndRequest(object sender, EventArgs e)
{
if (Context.Response.StatusCode == 401)
{ // this is important, because the 401 is not an error by default!!!
throw new HttpException(401, "You are not authorised");
}
}
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<html>
<head>
<title> Error</title>
</head>
<body>
<div>
@{
int x=ViewBag.status;
}
<p style=" color: Red;">
@switch (x) {
case 401: {
<span>PAGE NOT FOUND</span>
}
break;
case 403: {
<span>FORBIDDEN</span>
}
break;
case 404: {
<span>We have experienced a 404 error.Site temporarily down</span>
}
break;
case 500: {
<span>please refresh page and try again!</span>
}
break;
//and more cases for more error-codes...
default: {
<span>Unknown error!!!</span>
}
break;
}
</p>
</div>
</body>
</html>
The code can give customized page for all the errors in cases .But now i want to catch all exceptions from try -catch method like db exceptions and display it in a customized way.
example : "null value exception or connection string exceptions" .
My doubt is how can I give the case o something for that. I have no idea to continue?
But now i want to catch all exceptions from try -catch method like db exceptions and display it in a customized way
Two options:
Let the exceptions escape ( throw
without arguments in a catch
will rethrow the same exception), and follow through the normal route for otherwise unhanded exceptions.
Redirect, as for any other controller/action to ErrorController.Action
#2 leaves the issue of passing the exception object to the controller (which will need a different code path in the error controller to pick up the two methods the Exception
instance is passed), so #1 is generally the easier option.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.