React обработка ошибок axios

axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

Using the validateStatus config option, you can define HTTP code(s) that should throw an error.

axios.get('/user/12345', {
  validateStatus: function (status) {
    return status < 500; // Resolve only if the status code is less than 500
  }
})

Using toJSON you get an object with more information about the HTTP error.

axios.get('/user/12345')
  .catch(function (error) {
    console.log(error.toJSON());
  });

Github: https://github.com/SeanningTatum/10-April-2021-Error-Handling

Slides: https://docs.google.com/presentation/d/1IT1d_hi2m1CiYVUwC5ubFM__Pych7nb_Cilhv8Hx7rU/edit?usp=sharing

Problem Statement

unknown error

Guess where this error came from? Upon first inspection — calling /api/items is the problem. But this raises a number of questions, such as

  • Which route called this? You might have inner routes.

  • Which file? My project is scaling and has over 100 possible files where that could’ve come from.

  • A 400 error can come in different shapes

    • Form validation error?

      • Which form value in particular? And what type of validation errors?
    • Problems with the Query Params?

    • etc.

better error

Now take a look at this error message.

  • Clear Error Type
  • Clear Error Message
  • Stack Trace is very clear, it tells you exactly which file and line the error was called
  • There’s a source map link you can click which lets you view the code in the browser.

If you click the link you’d see something like this

source map error

Now that’s more like it! Even people who are new the project can start debugging right away!

How do we add this?

Axios allows you to intercept requests and responses before they they are handled by .then and .catch. These are called interceptors (read more here).

If you’ve clicked the link you can create an instance and intercept the response like so.

// utils/axios.js

const instance = axios.create();

instance.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
}, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
});

export default instance

So far this is the default error handling that axios is already providing us, let’s try meddling around with it to see how to play around with the interceptors.

instance.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
}, function (error) {
  
    if (error.code.status === 400) {
      return Promise.reject({
        message: "You've recieved an error!"
      })
    }
  
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
});

Let’s see what that does in the console.

error object

Probably what you were expecting! It returned our custom object and even told us where the error was caught! Assuming you’ve wrapped it around a try/catch block or a .catch.

But this brings us to another problem — as we’re trying to scale and maintain our systems, from a coding point this is still not ‘simple enough’. We need to handle a lot of edge cases for errors, it’s like our data structures and algorithms class where we have to consider every edge case possible and can easily end up like this.

function fetchData() {
  try {
    const data = await axios.get('/data')
    
    return data
  } catch (err) {
    if (err.code === '404') {
      setError('Object does not exist.')
      return
    }
    
    if (err.name === 'err001-auth') {
      history.push('/login')
      return
    }
    
    if (err.body.validation.length > 0) {
      const validations = err.body.validation.map(err => err.message)
      setValidations(validations)
      return
    }
  }
}

At the moment it’s not hard to read or understand, but as errors get more complicated such as multiple permissions, handling errors from 3rd party apis and having different formats of errors it can get easily get out of hand if left unchecked. So what should we do? How can we make it readable in the code, abstract errors and easily debug?

function fetchData() {
  try {
    const data = await axios.get('/data')
    
    return data
  } catch (error) {
    if (error instanceof NotFoundError) {
      setError('Object does not exist.')
      return
    }
    
    if (error instanceof AuthorizationError) {
      // View what permissions were needed to access content
      console.log(error.permissions())
      
      history.push('/login')
      return
    }
    
    if (error instanceof ValidationError) {
      // Generate readable error message to display to user
      setError(error.generateErrorMessage())
      
      // Format Errors from Server
      setFormValueErrors(error.formatErrors())
      return
    }
    
    if (error instanceof ServerError) {
      history.push('/server-down')
      return
    }
  }
}

Now without even knowing anything about error codes and the different error conventions — I can read it what type of error it is in plain english and the error class has abstracted helper methods that I do not need to know about that are provided for me. Good for me 1 year later and any new developers that are joining the project!

Now let’s see how we can catch custom error objects. First we’re going to have to create one!

// utils/customErrors.js

export class BadRequestError extends Error {
  constructor(errors) {
    super('Something was wrong with your Request Body');
    this.name = 'BadRequestError';
    this.errors = errors || [];
  }

  // Assuming your data looks like this
  // {
  //   "errors": [
  //     {
  //       "location": "body",
  //       "msg": "Invalid value",
  //       "param": "username"
  //     },
  //     ...
  //   ]
  // }
  formatErrorsIntoReadableStr() {
    let str = 'There are formatting issues with';
    this.errors.forEach((error) => {
      str += `${error.param}, `;
    });

    return str;
  }
  
  // More custom code here if you want.
}

Now back into `utils/axios.js` let’s throw our custom error instead of a simple object

// utils/axios.js

// NEW:- Import New Error Class
import {BadRequestError} from './errors'

instance.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
}, function (error) {
  
    if (error.code.status === 400) {
      // NEW:- Throw New Error
      throw new BadRequestError()
    }
  
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
});
function fetchData() {
  try {
    const data = await axios.get('/data')
    
    return data
  } catch (error) { 
    // Catch your new error here!
    if (error instanceof BadRequestError) {
      // Generate readable error message to display to user
      setError(error.formatErrorsIntoReadableStr())
      return
    }
    
  }
}

Now with this simple code and some object oriented programming that you were probably taught in college, frontend life has become easier.

I have a React component that calls a function getAllPeople:

componentDidMount() {
   getAllPeople().then(response => {
      this.setState(() => ({ people: response.data }));
    });
  } 

getAllPeople is in my api module:

export function getAllPeople() {
  return axios
    .get("/api/getAllPeople")
    .then(response => {
      return response.data;
    })
    .catch(error => {
      return error;
    });
}

I think this is a very basic question, but assuming I want to handle the error in my root component (in my componentDidMount method), not in the api function, how does this root component know whether or not I the axios call returns an error? I.e. what is the best way to handle errors coming from an axios promise?

asked Oct 29, 2017 at 21:32

GluePear's user avatar

GluePearGluePear

7,26520 gold badges67 silver badges120 bronze badges

Better way to handle API error with Promise catch method*.

axios.get(people)
    .then((response) => {
        // Success
    })
    .catch((error) => {
        // Error
        if (error.response) {
            // The request was made and the server responded with a status code
            // that falls out of the range of 2xx
            // console.log(error.response.data);
            // console.log(error.response.status);
            // console.log(error.response.headers);
        } else if (error.request) {
            // The request was made but no response was received
            // `error.request` is an instance of XMLHttpRequest in the 
            // browser and an instance of
            // http.ClientRequest in node.js
            console.log(error.request);
        } else {
            // Something happened in setting up the request that triggered an Error
            console.log('Error', error.message);
        }
        console.log(error.config);
    });

answered May 31, 2018 at 3:39

Sagar's user avatar

SagarSagar

4,4933 gold badges32 silver badges37 bronze badges

0

The getAllPeople function already returns the data or error message from your axios call. So, in componentDidMount, you need to check the return value of your call to getAllPeople to decide whether it was an error or valid data that was returned.

componentDidMount() {
   getAllPeople().then(response => {
      if(response!=error) //error is the error object you can get from the axios call
         this.setState(() => ({ people: response}));
      else { // your error handling goes here
       }
    });
  } 

If you want to return a promise from your api, you should not resolve the promise returned by your axios call in the api. Instead you can do the following:

export function getAllPeople() {
  return axios.get("/api/getAllPeople");
}

Then you can resolve in componentDidMount.

componentDidMount() {
   getAllPeople()
   .then(response => {          
         this.setState(() => ({ people: response.data}));
     })
   .catch(error => { 
         // your error handling goes here
     }
  } 

Yana Trifonova's user avatar

answered Oct 29, 2017 at 21:47

palsrealm's user avatar

palsrealmpalsrealm

5,0931 gold badge20 silver badges25 bronze badges

2

My suggestion is to use a cutting-edge feature of React. Error Boundaries

This is an example of using this feature by Dan Abramov.
In this case, you can wrap your component with this Error Boundary component.
What is special for catching the error in axios is that you can use
interceptors for catching API errors.
Your Error Boundary component might look like

import React, { Component } from 'react';

const errorHandler = (WrappedComponent, axios) => {
  return class EH extends Component {
    state = {
      error: null
    };

    componentDidMount() {
      // Set axios interceptors
      this.requestInterceptor = axios.interceptors.request.use(req => {
        this.setState({ error: null });
        return req;
      });

      this.responseInterceptor = axios.interceptors.response.use(
        res => res,
        error => {
          alert('Error happened');
          this.setState({ error });
        }
      );
    }

    componentWillUnmount() {
      // Remove handlers, so Garbage Collector will get rid of if WrappedComponent will be removed 
      axios.interceptors.request.eject(this.requestInterceptor);
      axios.interceptors.response.eject(this.responseInterceptor);
    }

    render() {
      let renderSection = this.state.error ? <div>Error</div> : <WrappedComponent {...this.props} />
      return renderSection;
    }
  };
};

export default errorHandler;

Then, you can wrap your root component passing axios instance with it

errorHandler(Checkout, api)

As a result, you don’t need to think about error inside your component at all.

answered May 7, 2018 at 18:51

Yevhenii Herasymchuk's user avatar

4

I just combined both answers by Yevhenii Herasymchuk and GeorgeCodeHub, fixed some mistakes and ported it into React hooks. So here is my final working version:

// [project-directory]/src/lib/axios.js

import Axios from 'axios';

const axios = Axios.create({
  baseURL: process.env.NEXT_PUBLIC_BACKEND_URL,
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
  },
  withCredentials: true,
});

export default axios;


// [project-directory]/src/components/AxiosErrorHandler.js

import {useEffect} from 'react';
import axios from '@/lib/axios';

const AxiosErrorHandler = ({children}) => {
  useEffect(() => {
    // Request interceptor
    const requestInterceptor = axios.interceptors.request.use((request) => {
      // Do something here with request if you need to
      return request;
    });

    // Response interceptor
    const responseInterceptor = axios.interceptors.response.use((response) => {
      // Handle response here

      return response;
    }, (error) => {
      // Handle errors here
      if (error.response?.status) {
        switch (error.response.status) {
          case 401:
            // Handle Unauthenticated here
            break;
          case 403:
            // Handle Unauthorized here
            break;
          // ... And so on
        }
      }

      return error;
    });

    return () => {
      // Remove handlers here
      axios.interceptors.request.eject(requestInterceptor);
      axios.interceptors.response.eject(responseInterceptor);
    };
  }, []);

  return children;
};

export default AxiosErrorHandler;

Usage:

// Wrap it around your Layout or any component that you want

return (
  <AxiosErrorHandler>
    <div>Hello from my layout</div>
  </AxiosErrorHandler>
);

answered Feb 1 at 15:59

Hooman Limouee's user avatar

Hooman LimoueeHooman Limouee

1,1532 gold badges21 silver badges43 bronze badges

1

There is 2 options to handle error with axios in reactjs

  1. Using catch method:

    axios.get(apiUrl).then(()=>{
    //respons
    }).catch((error)=>{
    //handle error here
    })

  2. try catch

    try {
    const res = await axios.get(apiUrl);
    } catch(err){
    //handle error here…
    }

answered Mar 13 at 9:29

Khurshid Ansari's user avatar

Khurshid AnsariKhurshid Ansari

4,6682 gold badges33 silver badges52 bronze badges

You could check the response before setting it to state. Something like

componentDidMount() {
   getAllPeople().then(response => {
       // check if its actual response or error
        if(error) this.setState(() => ({ error: response }));
        else this.setState(() => ({ people: response}));
    });
  }

Its relying on the fact that axios will return different objects for success and failures.

answered Oct 29, 2017 at 21:40

Hozefa's user avatar

HozefaHozefa

1,6866 gold badges22 silver badges34 bronze badges

The solution from Yevhenii Herasymchuk was very close to what I needed however, I aimed for an implementation with functional components so that I could use Hooks and Redux.

First I created a wrapper:

export const http = Axios.create({
    baseURL: "/api",
    timeout: 30000,
});

function ErrorHandler(props) {

useEffect(() => {
    //Request interceptor
    http.interceptors.request.use(function (request) {
        // Do something here with Hooks or something else
        return request;
    });

    //Response interceptor
    http.interceptors.response.use(function (response) {
        if (response.status === 400) {
            // Do something here with Hooks or something else
            return response;
        }
        return response;
    });
}, []);

return props.children;
}

export default ErrorHandler;

Then I wrapped the part of the project that I needed to check how axios behaved.

<ErrorHandler>
  <MainPage/>
</ErrorHandler>

Lastly, I import the axios instance(http) wherever I need it in the project.

Hope it helps anyone that wishes for a different approach.

answered Sep 8, 2021 at 13:57

GeorgeCodeHub's user avatar

1

React

Когда вы делаете вызов к бэкенд API с axios, вы должны рассмотреть, что делать с блоком .catch() вашего промиса. Теперь вам может показаться, что ваш API высокодоступен и он будет работать 24/7, что рабочий процесс пользователя довольно ясен, ваш JavaScript вменяем и у вас есть модульные тесты. Поэтому, когда вы смотрите на блок catch при выполнении запросов с помощью axios, вы можете подумать: “Ну… Я просто использую console.log. Все будет в порядке.”

axios.get('/my-highly-available-api')
  .then(response => { 
    // do stuff 
  }) 
  .catch(err => { 
    // what now? 
    console.log(err); 
  })

Но есть еще так много вещей, которые находятся вне вашего контроля, которые могут вызвать ошибки при выполнении запросов API — и вы, вероятно, даже не знаете, что они происходят!

Эта статья посвящена в основном ошибкам, которые вы видите в браузере. На бэкенде тоже все может выглядеть довольно забавно. Просто взгляните на три вещи, которые вы можете увидеть в своих бэкенд журналах.

Ниже приведены три типа ошибок, которые могут появиться, и как их обрабатывать при использовании axios.

Отлов ошибок Axios

Ниже приведен фрагмент кода, который я начал включать в несколько проектов JS:

axios.post(url, data)
  .then(res => { 
    // do good things 
  }) 
  .catch(err => { 
    if (err.response) { 
      // client received an error response (5xx, 4xx)
    } else if (err.request) { 
      // client never received a response, or request never left 
    } else { 
      // anything else 
    } 
  })

Каждое условие предназначено для фиксации различного типа ошибки.

Проверка error.response

Если ваш объект error содержит поле response, это означает, что сервер ответил с ошибкой 4xx/5xx. Обычно это та ошибка, с которой мы лучше всего знакомы и с которой легче всего справиться.

Применяйте следующее: “Показать страницу 404 Not Found / сообщение об ошибке, если ваш API возвращает 404.” Покажите другое сообщение об ошибке, если ваш бэкенд возвращает 5xx или вообще ничего не возвращает. Вы может показаться, что ваш хорошо сконструированный бэкенд не будет генерировать ошибки, но это всего лишь вопрос времени, а не “если”.

Проверка error.request

Второй класс ошибок — это когда у вас нет ответа, но есть поле request, прикрепленное к ошибке. Когда же это происходит? Это происходит, когда браузер смог сделать запрос, но по какой-то причине не получил ответа. Это может произойти, если:

• Вы находитесь в обрывочной сети (например, в метро или используете беспроводную сеть здания).

• Ваш бэкенд зависает на каждом запросе и не возвращает ответ вовремя.

• Вы делаете междоменные запросы, но вы не авторизованы, чтобы их делать.

• Вы делаете междоменные запросы, и вы авторизованы, но бэкенд API возвращает ошибку.

Одна из наиболее распространенных версий этой ошибки имела бесполезное сообщение “Ошибка сети”. У нас есть API для фронтенда и бэкенда, размещенные в разных доменах, поэтому каждый вызов к бэкенд API — это междоменный запрос.

Из-за ограничений безопасности на JS в браузере, если вы делаете запрос API, и он не работает из-за плохих сетей, единственная ошибка, которую вы увидите — это “Ошибка сети”, которая невероятно бесполезна. Она может означать что угодно: от “Ваше устройство не имеет подключения к Интернету” до “Ваши OPTIONS вернули 5xx” (если вы делаете запросы CORS). Причина ошибки сети хорошо описана в этом ответе на StackOverflow.

Все остальные типы ошибок

Если ваш объект error не содержит поля response или request, это означает, что это не ошибка axios и, скорее всего, в вашем приложении что-то еще не так. Сообщение об ошибке + трассировка стека должны помочь вам понять, откуда оно исходит.

Как вам их исправить?

Ухудшение пользовательского опыта

Все это зависит от вашего приложения. Для проектов, над которыми я работаю, для каждой функции, использующей эти конечные точки, мы ухудшаем пользовательский опыт.

Например, если запрос не выполняется и страница бесполезна без этих данных, то у нас будет большая страница ошибок, которая появится и предложит пользователям выход — иногда это всего лишь кнопка “Обновить страницу”.

Другой пример: если запрос на изображение профиля в потоке социальных сетей не выполняется, мы можем показать изображение-плейсхолдер и отключить изменения изображения профиля вместе с всплывающим уведомлением, объясняющим, почему кнопка “Обновить изображение профиля” отключена. Однако показывать предупреждение с надписью “422 необработанных объекта” бесполезно для пользователя.

Обрывистые сети

Веб-клиент, над которым я работаю, используется в школьных сетях, которые бывают совершенно ужасны. Доступность бэкенда едва ли имеет к этому какое-то отношение. Запрос иногда не выходит из школьной сети.

Для решения такого рода периодических проблем с сетью, мы добавили axios-retry, что решило большое количество ошибок, которые мы наблюдали в продакшне. Это было добавлено в нашу настройку axios:

const _axios = require('axios') 
const axiosRetry = require('axios-retry') 
const axios = _axios.create() 
// https://github.com/softonic/axios-retry/issues/87 const retryDelay = (retryNumber = 0) => { 
  const seconds = Math.pow(2, retryNumber) * 1000; 
  const randomMs = 1000 * Math.random(); 
  return seconds + randomMs; 
}; 
axiosRetry(axios, { 
  retries: 2, 
  retryDelay, 
  // retry on Network Error & 5xx responses 
  retryCondition: axiosRetry.isRetryableError, 
}); 
module.exports = axios;

Мы увидели, что 10% наших пользователей (которые находятся в плохих школьных сетях) периодически наблюдали ошибки сети, но число снизилось до <2% после добавления автоматических повторных попыток при сбое.

Скриншот количества ошибок сети, как они появляются в браузере New Relic. <1% запросов неверны. Это подводит меня к последнему пункту.

Добавляйте отчеты об ошибках в свой интерфейс

Полезно иметь отчеты об ошибках и событиях фронтенда, чтобы вы знали, что происходит в разработке, прежде чем ваши пользователи сообщат вам о них. На моей основной работе мы используем браузер New Relic для отправки событий ошибок с фронтенда. Поэтому всякий раз, когда мы ловим исключение, мы регистрируем сообщение об ошибке вместе с трассировкой стека (хотя это иногда бесполезно с минимизированными пакетами) и некоторыми метаданными о текущем сеансе, чтобы попытаться воссоздать его.

Другие инструменты, используемые нами— Sentry + SDK браузер, Rollbar и целая куча других полезных инструментов, перечисленных на GitHub.

Заключение

Если вы больше ничего не можете выжать из этого, сделайте одно: перейдите в свою кодовую базу и просмотрите, как вы обрабатываете ошибки с помощью axios.

  • Проверьте, выполняете ли вы автоматические повторы, и, если нет, добавьте axios-retry.
  • Проверьте, что вы отлавливаете ошибки и сообщаете пользователю, что что-то произошло. Использовать только axios.get(...).catch(console.log) недостаточно.

Читайте также:

  • React TypeScript: Основы и лучшие практики
  • Первые шаги в анимации React Native
  • Как предотвратить состояние гонки с помощью React Context API

Перевод статьи Danny Perez: How to Handle API Errors in Your Web App Using Axios

Introduction

I really love the problem/solution. approach. We see some problem, and then, a really nice solution. But for this talking, i think we need some introduction as well.

When you develop an web application, you generally want’s to separate the frontend and backend. Fo that, you need something that makes the communication between these guys.

To illustrate, you can build a frontend (commonly named as GUI or user interface) using vanilla HTML, CSS and Javascript, or, frequently, using several frameworks like Vue, React and so many more avaliable online. I marked Vue because it’s my personal preference.

Why? I really don’t study the others so deeply that i can’t assure to you that Vue is the best, but i liked the way he works, the syntax, and so on. It’s like your crush, it’s a personal choice.

But, beside that, any framework you use, you will face the same problem:_ How to communicate with you backend_ (that can be written in so many languages, that i will not dare mention some. My current crush? Python an Flask).

One solution is to use AJAX (What is AJAX? Asynchronous JavaScript And XML). You can use XMLHttpRequest directly, to make requests to backend and get the data you need, but the downside is that the code is verbose. You can use Fetch API that will make an abstraction on top of XMLHttpRequest, with a powerfull set of tools. Other great change is that Fetch API will use Promises, avoiding the callbacks from XMLHttpRequest (preventing the callback hell).

Alternatively, we have a awesome library named Axios, that have a nice API (for curiosity purposes, under the hood, uses XMLHttpRequest, giving a very wide browser support). The Axios API wraps the XMLHttpRequest into Promises, different from Fetch API. Beside that, nowadays Fetch API is well supported by the browsers engines available, and have polyfills for older browsers. I will not discuss which one is better because i really think is personal preference, like any other library or framework around. If you dont’t have an opinion, i suggest that you seek some comparisons and dive deep articles. Has a nice article that i will mention to you written by Faraz Kelhini.

My personal choice is Axios because have a nice API, has Response timeout, automatic JSON transformation, and Interceptors (we will use them in the proposal solution), and so much more. Nothing that cannot be accomplished by Fetch API, but has another approach.

The Problem

Talking about Axios, a simple GET HTTP request can be made with these lines of code:

import axios from 'axios'

//here we have an generic interface with basic structure of a api response:
interface HttpResponse<T> {
  data: T[]
}

// the user interface, that represents a user in the system
interface User {
  id: number
  email: string
  name: string
}

//the http call to Axios
axios.get<HttpResponse<User>>('/users').then((response) => {
  const userList = response.data
  console.log(userList)
})

Enter fullscreen mode

Exit fullscreen mode

We’ve used Typescript (interfaces, and generics), ES6 Modules, Promises, Axios and Arrow Functions. We will not touch them deeply, and will presume that you already know about them.

So, in the above code, if everything goes well, aka: the server is online, the network is working perfectly, so on, when you run this code you will see the list of users on console. The real life isn’t always perfect.

We, developers, have a mission:

Make the life of users simple!

So, when something is go bad, we need to use all the efforts in ours hands to resolve the problem ourselves, without the user even notice, and, when nothing more can be done, we have the obligation to show them a really nice message explaining what goes wrong, to easy theirs souls.

Axios like Fetch API uses Promises to handle asynchronous calls and avoid the callbacks that we mention before. Promises are a really nice API and not to difficult to understand. We can chain actions (then) and error handlers (catch) one after another, and the API will call them in order. If an Error occurs in the Promise, the nearest catch is found and executed.

So, the code above with basic error handler will become:

import axios from 'axios'

//..here go the types, equal above sample.

//here we call axios and passes generic get with HttpResponse<User>.
axios
  .get<HttpResponse<User>>('/users')
  .then((response) => {
    const userList = response.data
    console.log(userList)
  })
  .catch((error) => {
    //try to fix the error or
    //notify the users about somenthing went wrong
    console.log(error.message)
  })

Enter fullscreen mode

Exit fullscreen mode

Ok, and what is the problem then? Well, we have a hundred errors that, in every API call, the solution/message is the same. For curiosity, Axios show us a little list of them: ERR_FR_TOO_MANY_REDIRECTS, ERR_BAD_OPTION_VALUE, ERR_BAD_OPTION, ERR_NETWORK, ERR_DEPRECATED, ERR_BAD_RESPONSE, ERR_BAD_REQUEST, ERR_CANCELED, ECONNABORTED, ETIMEDOUT. We have the HTTP Status Codes, where we found so many errors, like 404 (Page Not Found), and so on. You get the picture. We have too much common errors to elegantly handle in every API request.

The very ugly solution

One very ugly solution that we can think of, is to write one big ass function that we increment every new error we found. Besides the ugliness of this approach, it will work, if you and your team remember to call the function in every API request.

function httpErrorHandler(error) {
  if (error === null) throw new Error('Unrecoverable error!! Error is null!')
  if (axios.isAxiosError(error)) {
    //here we have a type guard check, error inside this if will be treated as AxiosError
    const response = error?.response
    const request = error?.request
    const config = error?.config //here we have access the config used to make the api call (we can make a retry using this conf)

    if (error.code === 'ERR_NETWORK') {
      console.log('connection problems..')
    } else if (error.code === 'ERR_CANCELED') {
      console.log('connection canceled..')
    }
    if (response) {
      //The request was made and the server responded with a status code that falls out of the range of 2xx the http status code mentioned above
      const statusCode = response?.status
      if (statusCode === 404) {
        console.log('The requested resource does not exist or has been deleted')
      } else if (statusCode === 401) {
        console.log('Please login to access this resource')
        //redirect user to login
      }
    } else if (request) {
      //The request was made but no response was received, `error.request` is an instance of XMLHttpRequest in the browser and an instance of http.ClientRequest in Node.js
    }
  }
  //Something happened in setting up the request and triggered an Error
  console.log(error.message)
}

Enter fullscreen mode

Exit fullscreen mode

With our magical badass function in place, we can use it like that:

import axios from 'axios'

axios
  .get('/users')
  .then((response) => {
    const userList = response.data
    console.log(userList)
  })
  .catch(httpErrorHandler)

Enter fullscreen mode

Exit fullscreen mode

We have to remember to add this catch in every API call, and, for every new error that we can graciously handle, we need to increase our nasty httpErrorHandler with some more code and ugly if's.

Other problem we have with this approach, besides ugliness and lack of mantenability, is that, if in one, only single one API call, i desire to handle different from global approach, i cannot do.

The function will grow exponentially as the problems that came together. This solution will not scale right!

The elegant and recommended solution

When we work as a team, to make them remember the slickness of every piece of software is hard, very hard. Team members, come and go, and i do not know any documentation good enough to surpass this issue.

In other hand, if the code itself can handle these problems on a generic way, do-it! The developers cannot make mistakes if they need do nothing!

Before we jump into code (that is what we expect from this article), i have the need to speak some stuff to you understand what the codes do.

Axios allow we to use something called Interceptors that will be executed in every request you make. It’s a awesome way of checking permission, add some header that need to be present, like a token, and preprocess responses, reducing the amount of boilerplate code.

We have two types of Interceptors. Before (request) and After (response) an AJAX Call.

It’s use is simple as that:

//Intercept before request is made, usually used to add some header, like an auth
const axiosDefaults = {}
const http = axios.create(axiosDefaults)
//register interceptor like this
http.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    const token = window.localStorage.getItem('token') //do not store token on localstorage!!!
    config.headers.Authorization = token
    return config
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error)
  }
)

Enter fullscreen mode

Exit fullscreen mode

But, in this article, we will use the response interceptor, because is where we want to deal with errors. Nothing stops you to extend the solution to handle request errors as well.

An simple use of response interceptor, is to call ours big ugly function to handle all sort of errors.

As every form of automatic handler, we need a way to bypass this (disable), when we want. We are gonna extend the AxiosRequestConfig interface and add two optional options raw and silent. If raw is set to true, we are gonna do nothing. silent is there to mute notifications that we show when dealing with global errors.

declare module 'axios' {
  export interface AxiosRequestConfig {
    raw?: boolean
    silent?: boolean
  }
}

Enter fullscreen mode

Exit fullscreen mode

Next step is to create a Error class that we will throw every time we want to inform the error handler to assume the problem.

export class HttpError extends Error {
  constructor(message?: string) {
    super(message) // 'Error' breaks prototype chain here
    this.name = 'HttpError'
    Object.setPrototypeOf(this, new.target.prototype) // restore prototype chain
  }
}

Enter fullscreen mode

Exit fullscreen mode

Now, let’s write the interceptors:

// this interceptor is used to handle all success ajax request
// we use this to check if status code is 200 (success), if not, we throw an HttpError
// to our error handler take place.
function responseHandler(response: AxiosResponse<any>) {
  const config = response?.config
  if (config.raw) {
    return response
  }
  if (response.status == 200) {
    const data = response?.data
    if (!data) {
      throw new HttpError('API Error. No data!')
    }
    return data
  }
  throw new HttpError('API Error! Invalid status code!')
}

function responseErrorHandler(response) {
  const config = response?.config
  if (config.raw) {
    return response
  }
  // the code of this function was written in above section.
  return httpErrorHandler(response)
}

//Intercept after response, usually to deal with result data or handle ajax call errors
const axiosDefaults = {}
const http = axios.create(axiosDefaults)
//register interceptor like this
http.interceptors.response.use(responseHandler, responseErrorHandler)

Enter fullscreen mode

Exit fullscreen mode

Well, we do not need to remember our magical badass function in every ajax call we made. And, we can disable when we want, just passing raw to request config.

import axios from 'axios'

// automagically handle error
axios
  .get('/users')
  .then((response) => {
    const userList = response.data
    console.log(userList)
  })
  //.catch(httpErrorHandler) this is not needed anymore

// to disable this automatic error handler, pass raw
axios
  .get('/users', {raw: true})
  .then((response) => {
    const userList = response.data
    console.log(userList)
  }).catch(() {
    console.log("Manually handle error")
  })

Enter fullscreen mode

Exit fullscreen mode

Ok, this is a nice solution, but, this bad-ass ugly function will grow so much, that we cannot see the end. The function will become so big, that anyone will want to maintain.

Can we improve more? Oh yeahhh.

The IMPROVED and elegant solution

We are gonna develop an Registry class, using Registry Design Pattern. The class will allow you to register error handling by an key (we will deep dive in this in a moment) and a action, that can be an string (message), an object (that can do some nasty things) or an function, that will be executed when the error matches the key. The registry will have parent that can be placed to allow you override keys to custom handle scenarios.

Here are some types that we will use througth the code:

// this interface is the default response data from ours api
interface HttpData {
  code: string
  description?: string
  status: number
}

// this is all errrors allowed to receive
type THttpError = Error | AxiosError | null

// object that can be passed to our registy
interface ErrorHandlerObject {
  after?(error?: THttpError, options?: ErrorHandlerObject): void
  before?(error?: THttpError, options?: ErrorHandlerObject): void
  message?: string
  notify?: QNotifyOptions
}

//signature of error function that can be passed to ours registry
type ErrorHandlerFunction = (error?: THttpError) => ErrorHandlerObject | boolean | undefined

//type that our registry accepts
type ErrorHandler = ErrorHandlerFunction | ErrorHandlerObject | string

//interface for register many handlers once (object where key will be presented as search key for error handling
interface ErrorHandlerMany {
  [key: string]: ErrorHandler
}

// type guard to identify that is an ErrorHandlerObject
function isErrorHandlerObject(value: any): value is ErrorHandlerObject {
  if (typeof value === 'object') {
    return ['message', 'after', 'before', 'notify'].some((k) => k in value)
  }
  return false
}

Enter fullscreen mode

Exit fullscreen mode

So, with types done, let’s see the class implementation. We are gonna use an Map to store object/keys and a parent, that we will seek if the key is not found in the current class. If parent is null, the search will end. On construction, we can pass an parent,and optionally, an instance of ErrorHandlerMany, to register some handlers.

class ErrorHandlerRegistry {
  private handlers = new Map<string, ErrorHandler>()

  private parent: ErrorHandlerRegistry | null = null

  constructor(parent: ErrorHandlerRegistry = undefined, input?: ErrorHandlerMany) {
    if (typeof parent !== 'undefined') this.parent = parent
    if (typeof input !== 'undefined') this.registerMany(input)
  }

  // allow to register an handler
  register(key: string, handler: ErrorHandler) {
    this.handlers.set(key, handler)
    return this
  }

  // unregister a handler
  unregister(key: string) {
    this.handlers.delete(key)
    return this
  }

  // search a valid handler by key
  find(seek: string): ErrorHandler | undefined {
    const handler = this.handlers.get(seek)
    if (handler) return handler
    return this.parent?.find(seek)
  }

  // pass an object and register all keys/value pairs as handler.
  registerMany(input: ErrorHandlerMany) {
    for (const [key, value] of Object.entries(input)) {
      this.register(key, value)
    }
    return this
  }

  // handle error seeking for key
  handleError(
    this: ErrorHandlerRegistry,
    seek: (string | undefined)[] | string,
    error: THttpError
  ): boolean {
    if (Array.isArray(seek)) {
      return seek.some((key) => {
        if (key !== undefined) return this.handleError(String(key), error)
      })
    }
    const handler = this.find(String(seek))
    if (!handler) {
      return false
    } else if (typeof handler === 'string') {
      return this.handleErrorObject(error, { message: handler })
    } else if (typeof handler === 'function') {
      const result = handler(error)
      if (isErrorHandlerObject(result)) return this.handleErrorObject(error, result)
      return !!result
    } else if (isErrorHandlerObject(handler)) {
      return this.handleErrorObject(error, handler)
    }
    return false
  }

  // if the error is an ErrorHandlerObject, handle here
  handleErrorObject(error: THttpError, options: ErrorHandlerObject = {}) {
    options?.before?.(error, options)
    showToastError(options.message ?? 'Unknown Error!!', options, 'error')
    return true
  }

  // this is the function that will be registered in interceptor.
  resposeErrorHandler(this: ErrorHandlerRegistry, error: THttpError, direct?: boolean) {
    if (error === null) throw new Error('Unrecoverrable error!! Error is null!')
    if (axios.isAxiosError(error)) {
      const response = error?.response
      const config = error?.config
      const data = response?.data as HttpData
      if (!direct && config?.raw) throw error
      const seekers = [
        data?.code,
        error.code,
        error?.name,
        String(data?.status),
        String(response?.status),
      ]
      const result = this.handleError(seekers, error)
      if (!result) {
        if (data?.code && data?.description) {
          return this.handleErrorObject(error, {
            message: data?.description,
          })
        }
      }
    } else if (error instanceof Error) {
      return this.handleError(error.name, error)
    }
    //if nothings works, throw away
    throw error
  }
}
// create ours globalHandlers object
const globalHandlers = new ErrorHandlerRegistry()

Enter fullscreen mode

Exit fullscreen mode

Let’s deep dive the resposeErrorHandler code. We choose to use key as an identifier to select the best handler for error. When you look at the code, you see that has an order that key will be searched in the registry. The rule is, search for the most specific to the most generic.

const seekers = [
  data?.code, //Our api can send an error code to you personalize the error messsage.
  error.code, //The AxiosError has an error code too (ERR_BAD_REQUEST is one).
  error?.name, //Error has a name (class name). Example: HttpError, etc..
  String(data?.status), //Our api can send an status code as well.
  String(response?.status), //respose status code. Both based on Http Status codes.
]

Enter fullscreen mode

Exit fullscreen mode

This is an example of an error sent by API:

{
  "code": "email_required",
  "description": "An e-mail is required",
  "error": true,
  "errors": [],
  "status": 400
}

Enter fullscreen mode

Exit fullscreen mode

Other example, as well:

{
  "code": "no_input_data",
  "description": "You doesnt fill input fields!",
  "error": true,
  "errors": [],
  "status": 400
}

Enter fullscreen mode

Exit fullscreen mode

So, as an example, we can now register ours generic error handling:

globalHandlers.registerMany({
  //this key is sent by api when login is required
  login_required: {
    message: 'Login required!',
    //the after function will be called when the message hides.
    after: () => console.log('redirect user to /login'),
  },
  no_input_data: 'You must fill form values here!',
  //this key is sent by api on login error.
  invalid_login: {
    message: 'Invalid credentials!',
  },
  '404': { message: 'API Page Not Found!' },
  ERR_FR_TOO_MANY_REDIRECTS: 'Too many redirects.',
})

// you can registre only one:
globalHandlers.register('HttpError', (error) => {
  //send email to developer that api return an 500 server internal console.error
  return { message: 'Internal server errror! We already notify developers!' }
  //when we return an valid ErrorHandlerObject, will be processed as whell.
  //this allow we to perform custom behavior like sending email and default one,
  //like showing an message to user.
})

Enter fullscreen mode

Exit fullscreen mode

We can register error handler in any place we like, group the most generic in one typescript file, and specific ones inline. You choose. But, to this work, we need to attach to ours http axios instance. This is done like this:

function createHttpInstance() {
  const instance = axios.create({})
  const responseError = (error: any) => globalHandlers.resposeErrorHandler(error)
  instance.interceptors.response.use(responseHandler, responseError)
  return instance
}

export const http: AxiosInstance = createHttpInstance()

Enter fullscreen mode

Exit fullscreen mode

Now, we can make ajax requests, and the error handler will work as expected:

import http from '/src/modules/http'

// automagically handle error
http.get('/path/that/dont/exist').then((response) => {
  const userList = response.data
  console.log(userList)
})

Enter fullscreen mode

Exit fullscreen mode

The code above will show a Notify ballon on the user screen, because will fire the 404 error status code, that we registered before.

Customize for one http call

The solution doesn’t end here. Let’s assume that, in one, only one http request, you want to handle 404 differently, but just 404. For that, we create the dealsWith function below:

export function dealWith(solutions: ErrorHandlerMany, ignoreGlobal?: boolean) {
  let global
  if (ignoreGlobal === false) global = globalHandlers
  const localHandlers = new ErrorHandlerRegistry(global, solutions)
  return (error: any) => localHandlers.resposeErrorHandler(error, true)
}

Enter fullscreen mode

Exit fullscreen mode

This function uses the ErrorHandlerRegistry parent to personalize one key, but for all others, use the global handlers (if you wanted that, ignoreGlobal is there to force not).

So, we can write code like this:

import http from '/src/modules/http'

// this call will show the message 'API Page Not Found!'
http.get('/path/that/dont/exist')

// this will show custom message: 'Custom 404 handler for this call only'
// the raw is necessary because we need to turn off the global handler.
http.get('/path/that/dont/exist', { raw: true }).catch(
  dealsWith({
    404: { message: 'Custom 404 handler for this call only' },
  })
)

// we can turn off global, and handle ourselves
// if is not the error we want, let the global error take place.
http
  .get('/path/that/dont/exist', { raw: true })
  .catch((e) => {
    //custom code handling
    if (e.name == 'CustomErrorClass') {
      console.log('go to somewhere')
    } else {
      throw e
    }
  })
  .catch(
    dealsWith({
      404: { message: 'Custom 404 handler for this call only' },
    })
  )

Enter fullscreen mode

Exit fullscreen mode

The Final Thoughts

All this explanation is nice, but code, ah, the code, is so much better. So, i’ve created an github repository with all code from this article organized to you try out, improve and customize.

  • Click here to access the repo in github.

FOOTNOTES:

  • This post became so much bigger than a first realize, but i love to share my thoughts.
  • If you have some improvement to the code, please let me know in the comments.
  • If you see something wrong, please, fix-me!

Понравилась статья? Поделить с друзьями:
  • Realtek audio console ошибка при скачивании
  • React обработка ошибок сервера
  • React hook form обработка ошибок
  • React wad ошибка
  • Realtek audio console microsoft store ошибка