This video is available to students only

Centralizing Frontend Errors

In this lesson, we're going to centralize frontend errors

Centralizing frontend errors#

Till now, we were handling the errors separately inside our functions. However, we can use axios to centralize the errors. Like we were intercepting the request to add token to the header, we can intercept the response as well. If the response has an error, we can check its status and show the error accordingly.

Let's open agent.ts file and write axios.interceptors.response.use, and if there is response, we will simply return it; otherwise, we can get the error which will be of type axiosError. Let's destructure data and status from error response. Now we can use the switch statement to check the status code. Let's start with case 400. We can simply use notification from antd and use notification.error and the message will be data errorMessage because this is the property which is carrying the error message. Finally, we can break.

Same logic will be applied to 401 status which stands for unauthorized request. Let's copy it and replace 400 with 401. Now let's do it for status 403. Here, the message can be hardcoded because we are not using 403 in our server. Let's call it, You are not allowed to do that!. Status 404 can be the same, data.errorMessage. For status 500, we can write a custom message which will be Server error, try again later. For the default case, we will simply break from the loop and finally, we will return promise reject error response.

There is another use case where we have validation errors and validation errors can be more than one. Since validation errors are status 400, let's go on top and check if we have errors inside data; we can loop over them and store it somewhere. Let's create a const, validationErrors, which will be an array of string. Initial value can be an empty string. Now we can use for in loop const key in data.errors. Let's use an if condition to check if data errors with the key exists; we can push it inside the validationErrors. Since this is an error, we can throw validationErrors array and flat it. Notification error can stay in place because when we throw the error, it will stop the execution there. So if there are multiple errors, we can throw the error; otherwise, we can display it.

Remember we need validation errors inside register component, so let's go there. Inside submitUser function, we can get rid of this notification and check if err.error exists, because this is where the array of errors will exist. Now we can loop over err.error and show the val as an error. By doing this, we will be able to show multiple notifications. Let's also go to Signin component and get rid of the notification because our agent file is handling this. We can simply log the error.

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