In the previous post we saw how to create the Sitecore items needed to handle a page for 404 and another for 500 errors, as well as the necessary changes in some config files. Now, we will look at some changes in code to display the correct HTML code.
Let’s start by creating a new rendering in Sitecore. I first created a new Rendering Folder called “Test”, but that’s up to you (/sitecore/layout/Renderings/Test):
As you can see I created a function called “ErrorCode” in an “ErrorController” controller. Here is the detail and code in the controller:
I’m using GlassMapper for this since it is easier to get data from Sitecore this way. I will try to create a future blog post of how to use it in a project, but for now, I am just reading the item and parsing it into the correspondent template we already created.
Furthermore, this is the view that will actually display the correspondent HTML code in the response. A 404 in the case of a not found page and a 500 in the case of an Internal Server Error:
Here you can see a detail of what we are using in the view:
- TrySkipIisCustomErrors: Gets or sets a value that specifies whether IIS custom errors are disabled.
- StatusCode: An integer that represents the HTML code that the response will return. In our case 404 and 500. This, of course, comes from Sitecore.
- Status (commented as reference): A string representing the text of the status. This can be also come from Sitecore if you want to.
Finally, you will see something like this if you go to a not found page or when an internal server error occurs: