Create a plugin handle error for Nuxt.js by yourself

Tram Ho

Problems encountered

Currently, if we code with projects on Nuxt.js platform, the use of global functions is extremely convenient, avoiding code duplication and reducing the syntax of importing plugins, utils, … inside the component. So how to handle it, we will go to the following example.

Simple example

Currently we have 2 files: 1 plugin handle-error.js and config file of Nuxt.js. These plugins work to log messages and log status codes, we can handle them for 404 codes that allow redirecting of certain pages or 500 code to handle other types.

A lot of flexibility to customize the Error handle, general configuration for all components after calling the API for processing.

Setup config

From now on inside the component we can use this.$handleError(error) , no need to import before because registered as global.

For example:

Extend callback function

To be more flexible we can use the callback function inside the custom plugins handleError

Our onSearch function can then write more


Hopefully for this little example, people can integrate into the project related to Nuxt.js, as well as agree on general rules of many different types of global variables depending on the purpose of use.

Share the news now

Source : Viblo