This video is available to students only

Creating Errors Controller

In this lesson, we're going to create Errors Controller

We have made some great progress so far; we have set up our generic repository. We also know about the Specification pattern and how it works. However, if you look carefully at our controllers, we haven't set up anything that handles the errors. As dotnet developers, it's our job to make sure the errors and exceptions are handled well and are consistent. This is what we're going to do now.

We will create a new controller called ErrorsController. The purpose of this controller is just to see the errors our Server is going to return in different scenarios. First of all, let's derive it from the Base Controller, and generate a constructor. Inside, we will inject our StoreContext and call it context. Let's import it using Infrastructure and initialize field from parameter. We are going to create methods for the most common errors. Let's start with the notFound error; we will use HttpGet and call it notFound. Let's import it from Microsoft.AspNetCore.Mvc. We can now write the method, public ActionResult and simply call it NotFoundMethod. Inside, we will force our controller to send us the error message.

What we will do is pass an id which we know doesn't exist. We can create a new variable category which will find for the Id, let's say 42. Now, if category is equal to null, we will return the not found error, otherwise we will return Ok. We are checking it with null because the Find method returns null when nothing's found.

Let's copy it three more times, and in the first, change not found to server error. In the second, let's make it ServerErrorMethod. We can just try to return category in a string format, which we know is never gonna happen; you can't convert a null into a string, so it will give us 500 error.

Start a new discussion. All notification go to the author.