How to customize error pages on a system ASP.NET MVC?
How to display a friendlier page when an error occurs in my application asp.net mvc(and not that yellow page)?
3 answers
There is a special view for these cases, the Shared/Error.cshtml
(has to be this name).
Simply connect the customErrors
of your application to the Web.config :
<system.web>
<customErrors mode="On" />
</system.web>
If you want to display error details, such as action name, controller name or the exception, you can configure your view to receive a model of type HandleErrorInfo.
The only problem is that unfortunately this solution does not meet 404 errors (Page No found). O asp.net mvc does not so easily support this type of error.
To handle it you will need a write action of your own for this (a URL of your own). Example, for URL ~/erros/nao-encontrado
:
<customErrors mode="On">
<error statusCode="404" redirect="~/erros/nao-encontrado" />
</customErrors>
In this case you are given the original URL via query string:
http://localhost/erros/nao-encontrado?aspxerrorpath=/administracao/algum-cadastro
On my website I modified the Global.asax.cs and includes
protected void Application_Error(object sender, EventArgs e)
{
var app = (MvcApplication)sender;
var context = app.Context;
var ex = app.Server.GetLastError();
context.Response.Clear();
context.ClearError();
var httpException = ex as HttpException;
var routeData = new RouteData();
routeData.Values["controller"] = "errors";
routeData.Values["exception"] = ex;
routeData.Values["action"] = "http500";
if (httpException != null)
{
switch (httpException.GetHttpCode())
{
case 404:
routeData.Values["action"] = "http404";
break;
case 500:
routeData.Values["action"] = "http500";
break;
}
}
IController controller = new ErrorsController();
controller.Execute(new RequestContext(new HttpContextWrapper(context), routeData));
}
And I created a Controller
to manage the errors
public class ErrorsController : Controller
{
public ActionResult Http404(Exception exception)
{
Response.StatusCode = 404;
Response.ContentType = "text/html";
return View(exception);
}
public ActionResult Http500(Exception exception)
{
Response.StatusCode = 500;
Response.ContentType = "text/html";
return View(exception);
}
}
This way if you access a non-existent page you will be redirected to Controller Action Http404
Errors
.
If you are trying to access an item (e.g. a product) and it does not exist, you may throw an error 404.
Example URL: /produtos/detalhes/10
Produto x = db.GetProduto(10);
if (x == null)
throw new HttpException(404, "Not Found");
Vc can create an Error controler, returning to the error View according to the error generated
public class ErrorController : Controller
{
//Erro 500 Servidor
public ActionResult Index()
{
ViewBag.AlertaErro = "Ocorreu um Erro :(";
ViewBag.MensagemErro = "Tente novamente ou " +
"contate um Administrador";
return View("Error");
}
//Error 404
public ActionResult NotFound()
{
ViewBag.AlertaErro = "Ocorreu um Erro :(";
ViewBag.MensagemErro = "Não existe uma página para a URL informada";
return View("Error");
}
//Erro 401 permissão de execução
public ActionResult AccessDenied()
{
//ViewBag.AlertaErro = "Acesso Negado :(";
//ViewBag.MensagemErro = "Você não tem permissão para executar isso";
return PartialView("Error403");
}
Now in WebConfig, vc enters this Code:
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="500" />
<remove statusCode="404" />
<remove statusCode="403" />
<error statusCode="500" responseMode="ExecuteURL" path="/Error/Index" />
<error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
<error statusCode="403" responseMode="ExecuteURL" path="/Error/AccessDenied" />
</httpErrors>
Is very easy to understand, in practice it replaces the default error mensganes and will use the ones you configured in Controler