How reasonable is the special error handler for requests on frontend?

Viewed 16

I am using a special wrapper to handle requests error on Frontend.

My error handle (handle.js):

 async (handle, customCatch = () => {}) => {
  try {
    await handle();
  } catch (err) {
    if (err.response) if (await customCatch(err)) return;
    await notify.error('Error !');
  }
};

My example use:

handle(async () => {
    const users=await axios.get('/users')
  })

If the axios requests which in the handle are any error notify will an error alert. It is basic a request. If there aren't any error it will get users information as expected. It prevents duplicate code. Automatically show an error with notify. If we don't use the handle method we would use like this:

try{
  const users=await axios.get('/users')
}catch(err){
  notify.error('Error !');
}

Okey, I think it is very useful. If we want to handle an error that we know how we would use it ? Other my example:

 handle(async () => {
        await axios.post('example/login',{password:'test',username:'test'})
      }, (err) => {
        if (err.response.status === 400) {
          this.isWrongEmailOrPassword = true;
          return true;
        }
      })

If it gets 400 error we want to set to isWrongEmailOrPassword variable. So we know that may get 400 error. We can set a custom error handler for custom request error code.

Is correct way this handle method ? How reasonable ? If this way isn't correct way what is correct way ? Thank you.

0 Answers
Related