This video is available to students only

Handling Errors

In this lesson, we're going to manage our Error Responses

Handling errors#

We saw that the errors are inconsistent and we're going to fix them right now. Inside our API project, let's create a new folder called ErrorResponse, and a class with name ApiResponse. We want to share the status code of the error and message to the client, so let's create two new properties; first one will be of type int and it will be called Status code and the second one will be of type string and it will be called ErrorMessage. Also, we need to create a constructor with these two properties so that whenever this is called, we can pass the status code and the error message to it. Let's use quick fix and use just the Generate Constructor. Selecting this will create a constructor with these two properties.

By creating this constructor, we're giving us an option to create custom error messages, but we can also create some default ones, which will work depending on the status code. Let me make the default value of the error message to be null. If it's set by us, it will use that particular value and if not, we are going to create a function which will create custom error messages. So let's create that method and call it DefaultErrorMessage. It will be a private method because we want to use it just here. It will return a string of message, it's called DefaultErrorMessage and it will take status code of type int as the parameter.

Inside this method, we will use the switch statement to return the message depending on the status code. We will write return then the status code then switch. Inside curly brackets, we can write the status codes followed by the arrow, and then the associated message. For 400 status, we can write You have made a bad request, for 401, it will be You are not authorized, for 404, Resource not found and for 500, Internal Server error. For something that doesn't match any of these, we can write an underscore followed by the message, An error has ocurred.

Now, inside the constructor, we can check if errorMessage is null which is checked by two question marks. We can use the DefaultErrorMessage method which will take the status code. Now what we're going to do is use this class to show errors to the client.

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