Axios Interceptors and Try/Catch error handling

Viewed 249

In my React Native app, I handle each call to the api within a try/catch block and am also using axios interceptors to handle the errors that I get from the server.

The problem is that using both of them seems redundant since I'm already handling the errors with axios interceptors and have no need of the catch block. Yet removing the try/catch blocks result in an UnhandledPromiseRejectionWarning.

try/catch for api calls: (WILL REMOVE THE CONSOLE.LOG)

// Request to the server
const handleSubmit = async () => {
  try {
    const response = await axis.post('API_URL',{BODY});
    return response.data
  } catch (error) {
    console.log(error);
  }
};

axios interceptors:

// Intercept on response
axios.interceptors.response.use(
  res => {
    return res;
  },
  err => {
    // Error handling logic
    // ....................

    return Promise.reject(err);
  },
);

Is there any way I can keep using try/catch in my functions and still handle the errors with axios interceptors or just use axios interceptors and avoid the UnhandledPromiseRejectionWarning?

0 Answers
Related