简体   繁体   中英

How to centralize the error handling for API calls in react (with Axios)

I am using Axios for back end calls in my react application. For manageability I wrote a common function, used it for making back end calls. I need suggestion on how to centralize the error handling and best way to show it on UI.

    import Axios from "axios";


    // Backend api calls to :: 
    export default function apiService(requestParams) {
        const accessToken = sessionStorage.getItem("access_token");
        requestParams.headers = {
            'authorization': 'Bearer ' + accessToken,
            'Content-Type': 'application/json'
        };

        return Axios(requestParams);
    }

Use axios interceptors:

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Do something with response data
    return response;
  }, function (error) {
    // Do something with response error
    return Promise.reject(error);
  });

https://github.com/axios/axios

As stated above, you can use interceptors , or just configure your default client:

/**
 * Create an Axios Client with defaults
 */
const client = axios.create({
  baseURL: API.BASEURL,
  headers: {
    Authorization: getAuth(),
    'Access-Control-Max-Age': 1728000,
  },
});

/**
 * Request Wrapper with default success/error actions
 */
const request = (options) => {
  const onSuccess = (response) => options.raw ? response : response.data;
    // console.debug('Request Successful!', response);
    // If options.raw is true, return all response

  const onError = (error) => {
    // console.error('Request Failed:', error.config);

    if (error.response) {
      if (error.response.status === 401) {
        // console.error('Unauthorized');
      } else {
        // Request was made but server responded with something
        // other than 2xx
        // console.error('Status:', error.response.status);
        // console.error('Data:', error.response.data);
        // console.error('Headers:', error.response.headers);
      }
    } else {
      // Something else happened while setting up the request
      // triggered the error
      // console.error('Error Message:', error.message);
    }

    return Promise.reject(error.response || error.message);
  };

  return client(options)
    .then(onSuccess)
    .catch(onError);
};

We can use a dedicated java script method to make the API call and handle the error. Refer the below method.

const makeAPICall = async (url, method, payload = null, params = null) => {
  try {
    const response = await axios({
      method, url, payload, params
    });

    if (isEmpty(response.success) || response.success) {
      if(response.data.warnings) {
        warningHandler(response.data.warnings)
      }
      if(response.data.serviceErrors) {
        serviceErrorHandler(response.data.serviceErrors)
      }
      return response.data;
    }
    errorHanlder(response.data.error.message);

    return response.data;

  } catch (e) {
    return errorHandler(e);
  }
};

The Api will return serviceerror if there is a problem in the backend in that case we need to check whether there are any serviceerror object is available or not. Tf there is any service error then serviceErrorHandler will handle the error. In some cases API will fail with 500, 501, 404 etc error then in that case errorHandler function will handle those error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM