DEV Community

Muhammed Erdinç
Muhammed Erdinç

Posted on

Global Error Management in Nuxt.js Projects

Today, frontend projects have become more complex and dynamic compared to the past. Therefore, we have to consider many parameters while developing a frontend project. One of these parameters is error management.

With a error management, our project will not crash in the face of undesirable situations, the cause of the error will be shown to the user and the user experience will be increased.

In a frontend project, it is important to show the user the information about the operations that the application performs or cannot for some reason. This information can be displayed to the user with the snackbar.

Snackbar example

If you are developing a frontend project with Nuxt.js and you are making HTTP requests with axios, it is very easy to catch and process errors caused by HTTP requests globally with Axios Interceptors.

What are Axios Interceptors?

Axios interceptors are functions that are called on every HTTP request or response. HTTP requests and responses can be handled with the help of these functions before they are handled (by “then” or “catch”) within the application.

Global Error Management with Axios Interceptors

With axios-module, a special version of Axios for Nuxt, it is possible to do global error management with a simple plugin that you add to your project.
For this, respectively;

  1. Let’s create the axios.js file in the Plugins folder and include it in nuxt.config.js.
    export default {
    plugins: [
    '~/plugins/axios'
    ]
    }
    view raw nuxt.config.js hosted with ❤ by GitHub
    1. We can now catch and manage HTTP errors with $axios.onError. Also, onRequest, onResponse, onRequestError and onResponseError can be used together with onError as needed.
      export default function ({ $axios, redirect }) {
      $axios.onError(error => {
      const code = parseInt(error.response && error.response.status)
      if (code === 400) {
      redirect('/400')
      }
      })
      }
      view raw axios.js hosted with ❤ by GitHub
      HTTP requests and responses along with global error handling will help us build a clean and maintainable architecture. In addition, it will be much easier to eliminate possible errors and add new features, and the maintenance cost of the project will decrease.

References:

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay