I'm trying to set up custom errors for an MVC site. I have the 404 page working fine, but when testing a server error I get the default message:
Sorry, an error occurred while processing your request.
Instead of my custom page.
I have set this up in the web.config:
<customErrors mode="On" defaultRedirect="~/Error/500">
<error statusCode="404" redirect="~/Error/404" />
<error statusCode="500" redirect="~/Error/500" />
</customErrors>
My error controller is as follows:
public class ErrorController : Controller
{
[ActionName("404")]
public ActionResult NotFound()
{
return View();
}
[ActionName("500")]
public ActionResult ServerError()
{
return View();
}
}
I'm testing the 500
error page by throwing an exception in one of my views:
[ActionName("contact-us")]
public ActionResult ContactUs()
{
throw new DivideByZeroException();
return View();
}
Why is it that only 404 errors are handled? How can I display the error page for 500
errors?
There is a problem with the resource you are looking for, and it cannot be displayed. The first solution to a 500 internal server error is to refresh the page. If the error persists, you may try clearing the cookies, deactivating faulty plugins or themes, fixing the . htaccess file, or contacting your hosting provider.
The 500 Internal Server error could be caused by an error during the execution of any policy within Edge or by an error on the target/backend server. The HTTP status code 500 is a generic error response. It means that the server encountered an unexpected condition that prevented it from fulfilling the request.
IIS error The error 500.19 is an internal server error often occurring on a server using Microsoft IIS software. It indicates that the configuration data for the page is invalid. To solve the issue, delete the malformed XML element from the Web. config file or from the ApplicationHost.
Figured this out..
It was some boilerplate code left in the Global.asax.cs
when creating the project:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
In particular:
filters.Add(new HandleErrorAttribute());
This creates an new instance of HandleErrorAttribute
which is applied Globally to all of my views.
With no customization, if a view throws an error while utilizing this attribute, MVC will display the default Error.cshtml
file in the Shared
folder which is where the: "Sorry, an error occurred while processing your request."
came from.
From the documentation on HandleErrorAttribute:
By default, when an action method with the HandleErrorAttribute attribute throws any exception, MVC displays the Error view that is located in the ~/Views/Shared folder.
Commenting this line out solved the problem and allowed me to use custom error pages for 500 errors.
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