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());
});
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
GluePearGluePear
7,16420 gold badges67 silver badges118 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
SagarSagar
4,4033 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
}
}
answered Oct 29, 2017 at 21:47
palsrealmpalsrealm
5,04320 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
4
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
HozefaHozefa
1,6646 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
1
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
HoomanHooman
1,0832 gold badges19 silver badges42 bronze badges
1
There is 2 options to handle error with axios in reactjs
-
Using catch method:
axios.get(apiUrl).then(()=>{
//respons
}).catch((error)=>{
//handle error here
}) -
try catch
try {
const res = await axios.get(apiUrl);
} catch(err){
//handle error here…
}
answered Mar 13 at 9:29
Khurshid AnsariKhurshid Ansari
4,5632 gold badges32 silver badges50 bronze badges
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
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.
-
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
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.
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.
Axios — это библиотека JS, предоставляющая простой в применении интерфейс для выполнения HTTP-запросов в браузере и на стороне сервера. Она развернута на стандарте Promise API и предназначена для работы с асинхронными запросами.
Библиотека широко используется в различных проектах, включая React, Vue.js, Angular и другие фреймворки. Она позволяет разработчикам легко взаимодействовать с API и обрабатывать данные, получаемые от сервера.
Список преимуществ применения данной библиотеки в React:
- Простота применения: Имеет простой и легко понятный интерфейс, который делает его ясным в применении даже среди новичков. Это позволяет разработчикам быстро отправлять HTTP-запросы на сервер и получать от него ответы.
- Универсальность: Поддерживает не только браузеры, но и Node.js, что делает его идеальным выбором для применения на клиентской и на серверной стороне в проектах на React.
- Поддержка Promises: Возвращает объект Promises, что делает его идеальным для работы с современным синтаксисом JavaScript и облегчает обработку асинхронных операций.
- Интерсепторы: Позволяет использовать интерсепторы, чтобы запросы и ответы обрабатывались до их отправки и после получения. Это полезно для добавления заголовков, обработки ошибок и многого другого.
- Отмена запроса: Библиотека допускает отмену запросов, что позволяет улучшить производительность приложения и предотвратить лишние запросы.
- Поддержка заголовков и параметров запроса: Позволяет добавлять заголовки и параметры запроса, что полезно при передаче информации на сервер.
- Широкий функционал: Поддерживает все основные методы HTTP-запросов: GET, POST, PUT, DELETE и т.д. Он также поддерживает множество типов данных, таких как JSON, формы и текст.
- Обработка ошибок: Имеет встроенную обработку ошибок, что позволяет определять и обрабатывать ошибки, возникающие во время выполнения запросов.
Стоит сказать о требованиях, достаточных для работы с рассматриваемой библиотекой:
- Node.js 14 версии и позднее;
- Проект на React, организованный инструментом
create-react-app
; - Базовые знания JS, HTML и CSS.
В статье мы рассмотрим, как использовать Axios с React и приведем несколько примеров его применения.
Шаг 1. Перед началом работы с Axios необходимо выбрать рабочий проект:
cd project_name
Либо организовать новый, а затем перейти в него:
npx create-react-app project_name
cd project_name
Создадим React-приложение с названием timeweb
. Результаты создания продемонстрированы на картинке ниже.
Шаг 2. Далее необходимо поставить библиотеку, воспользовавшись пакетным менеджером npm
. Для этого выполним следующую команду в терминале:
npm install axios
Шаг 3. По окончанию загрузки необходимо импортировать библиотеку в компонент, требующий ее использования:
import axios from 'axios';
После успешной установки и импортирования библиотеки Axios в ваше React-приложение вы можете начать взаимодействие с ней.
GET-запрос
Чтобы отправить GET-запрос, используется метод axios.get()
, который принимает один параметр – адрес интернет-ресурса. Он не должен использоваться для отправки конфиденциальных данных, так как они могут быть видны в адресной строке браузера и логах сервера.
Для начала разработаем необходимый для реализации компонент.
Шаг 1. Перейдем из каталога приложения в директорию src
.
cd src
Шаг 2. Далее создаем файл с расширением .js
:
nano Test1.js
Шаг 3. Теперь переходим к написанию кода:
import React, { useEffect, useState } from "react";
import axios from "axios";function Test1() {
const [data, setData] = useState([]);
useEffect(() => {
axios
.get("https://jsonplaceholder.typicode.com/users")
.then((response) => {
setData(response.data);
})
.catch((error) => {
console.log(error);
});
}, []);
return (
<div>
<h1>Список пользователей:</h1>
<ul>
{data.map((user) => (
<li key={user.id}>
{user.name} ({user.email})
</li>
))}
</ul>
</div>
);
}
export default Test1;
В данном примере Test1
отправляет GET-запрос на указанный сервис и отображает список пользователей на странице. В компоненте используются два хука:
useEffect
для выполнения запроса;useState
для хранения данных, полученных от API.
Хук — это функция, которая позволяет использовать состояние и другие возможности React в функциональных компонентах. Если запрос не получилось отправить или обработать, то мы выводим ошибку в консоль.
Шаг 4. Проверим результат запроса. Он представлен на картинке ниже.
Обратите внимание, что в данном примере и во всех остальных используется API https://jsonplaceholder.typicode.com
, который предоставляет фейковые данные с целью тестирования. Вам следует заменить его на тот, который будет использоваться в проекте.
POST-запрос
POST-запросы используются для отправки данных на сервер, например, отправки формы с данными пользователя, отправки изображений или других файлов, а также для создания или обновления записей в базе данных.
POST-запросы могут быть безопасными, если они не изменяют состояние сервера, но они не являются идемпотентными, что означает, что при повторном отправлении может произойти изменение состояния сервера. Для идемпотентности они могут содержать специальный заголовок, например, Idempotency-Key
, который позволяет серверу определять, был ли запрос отправлен ранее.
POST-запросы также могут быть защищены с помощью токенов CSRF, чтобы предотвратить их подделку со стороны злоумышленников.
Чтобы отправить POST-запрос, необходимо вызвать метод post()
и передать ему данные и адрес интернет-ресурса, на который необходимо их отправить.
Шаг 1. Откроем ранее созданный файл для редактирования:
nano Test1.js
Шаг 2. Напишем новый код:
import React, { useState } from "react";
import axios from "axios";function Test1() {
const [data, setData] = useState({ name: "", email: "" });
const [response, setResponse] = useState("");
const handleChange = (event) => {
setData({ ...data, [event.target.name]: event.target.value });
};
const handleSubmit = (event) => {
event.preventDefault();
axios
.post("https://jsonplaceholder.typicode.com/users", data)
.then((response) => {
setResponse(response.data);
})
.catch((error) => {
console.log(error);
});
};
return (
<div>
<h1>Отправка данных на сервер</h1>
<form onSubmit={handleSubmit}>
<label>
Имя:
<input
type="text"
name="name"
value={data.name}
onChange={handleChange}
/>
</label>
<br />
<label>
Email:
<input
type="email"
name="email"
value={data.email}
onChange={handleChange}
/>
</label>
<br />
<button type="submit">Отправить</button>
</form>
{response && (
<p>
Данные успешно отправлены: {response.name} ({response.email})
</p>
)}
</div>
);
}
export default Test1;
В этом примере мы также применили useState
для хранения данных, введенных пользователем в форме, и данных, полученных от API. Мы также создали две функции:
handleChange
для обновления состояния формы при изменении пользователем данных;handleSubmit
для отправки POST-запроса при передаче формы.
Когда форма передается, мы отправляем POST-запрос и обрабатываем полученные данные, используя метод setResponse
. Если запрос не удалось отправить или обработать, то мы выводим ошибку в консоль.
Шаг 3. Проверим результат работы компонента. Он представлен на картинке ниже.
PUT-запрос
PUT-запросы отправляют данные в теле запроса на сервер, где они заменяют существующие данные ресурса. Они часто используются для обновления информации о пользователе, обновления контента на веб-страницах или для обновления данных в базе данных.
Чтобы отправить PUT-запрос, необходимо вызвать метод put()
и передать ему данные и URL-адрес ресурса, на который необходимо их отправить.
Шаг 1. Откроем файл компонента для редактирования:
nano Test1.js
Шаг 2. Снова перепишем код файла Test1.js
:
import React, { useState } from "react";
import axios from "axios";const Test1 = () => {
const [postData, setPostData] = useState({ id: "", title: "", body: "" });
const [putData, setPutData] = useState({ id: "", title: "", body: "" });
const handleInputChange = (event) => {
setPostData({ ...postData, [event.target.name]: event.target.value });
};
const handleSubmit = (event) => {
event.preventDefault();
axios
.put(`https://jsonplaceholder.typicode.com/posts/${postData.id}`, {
title: postData.title,
body: postData.body,
})
.then((response) => {
setPutData(response.data);
console.log(response);
})
.catch((error) => {
console.log(error);
});
};
return (
<div>
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="id">Уникальный номер: </label>
<input
type="text"
name="id"
value={postData.id}
onChange={handleInputChange}
/>
</div>
<div>
<label htmlFor="title">Заголовок: </label>
<input
type="text"
name="title"
value={postData.title}
onChange={handleInputChange}
/>
</div>
<div>
<label htmlFor="body">Основная информация: </label>
<input
type="text"
name="body"
value={postData.body}
onChange={handleInputChange}
/>
</div>
<button type="submit">Обновить данные</button>
</form>
<div>
<p>Ответ:</p>
<p>Уникальный номер:: {putData.id}</p>
<p>Заголовок: {putData.title}</p>
<p>Основная информация: {putData.body}</p>
</div>
</div>
);
};
export default Test1;
Здесь используется useState
для управления двумя состояниями:
postData
— содержит данные для отправки в PUT-запросе;putData
— содержит полученные в ответ на запрос данные.
Также определяем две функции:
handleInputChange
— обновляет состояние postData, при добавлении пользователем данных в форму;handleSubmit
— посылает PUT-запрос и обновляет состояниеputData
.
Наконец, мы отображаем полученные данные в putData
после успешного выполнения запроса.
Шаг 3. Проверим результат работы компонента. Он представлен на картинке ниже.
DELETE-запрос
Чтобы отправить DELETE-запрос, нужно вызвать метод delete()
и передать ему URL-адрес ресурса для удаления. После получения запроса сервер проверяет, есть ли указанный ресурс на сервере, и если он есть, то удаляет его. Если ресурса на сервере нет, он может вернуть ошибку 404 «Не найдено».
Шаг 1. Откроем файл компонента для редактирования:
nano Test1.js
Шаг 2. Снова перепишем код Test1.js
:
import React, { useState } from 'react';
import axios from 'axios';const Test1 = () => {
const [postId, setPostId] = useState(null);
const [response, setResponse] = useState(null);
const handleDelete = () => {
axios.delete(`https://jsonplaceholder.typicode.com/posts/${postId}`)
.then(res => setResponse(res))
.catch(err => setResponse(err));
}
return (
<div>
<input type="number" placeholder="Enter Post ID" onChange={(e) => setPostId(e.target.value)} />
<button onClick={handleDelete}>Delete Post</button>
{response && (
<div>
<h2>Response</h2>
<p>Status: {response.status}</p>
<p>Data: {JSON.stringify(response.data)}</p>
</div>
)}
</div>
);
}
export default Test1;
В этом компоненте мы создали форму, где пользователь может ввести ID записи, которую он хочет удалить, и отправить запрос на удаление при помощи метода axios.delete()
. Мы также обработали успешный ответ и ошибки при помощи методов then()
и catch()
соответственно.
Шаг 3. Проверим результат работы компонента. Он представлен на картинке ниже.
Обработка ошибок
Axios предоставляет удобный способ обработки ошибок, возникающих при отправке HTTP-запросов. then()
и catch()
принимают функции, которые будут выполнены в зависимости от статуса выполнения запроса (выполнен или произошла ошибка).
Шаг 1. Откроем файл компонента для редактирования:
nano Test1.js
Шаг 2. В очередной раз перепишем код файла Test1.js
:
import React, { useState } from "react";
import axios from "axios";const Test1 = () => {
const [error, setError] = useState(null);
const handleButtonClick = () => {
axios
.get("https://jsonplaceholder.typicode.com/posts/invalid-url")
.then((response) => {
console.log(response);
})
.catch((error) => {
setError(error);
});
};
return (
<div>
<button onClick={handleButtonClick}>Отправить GET-запрос</button>
{error && (
<div>
<h2>Сообщение об ошибке:</h2>
<p>{error.message}</p>
</div>
)}
</div>
);
};
export default Test1;
В примере выше создается состояние error
. Оно позволяет отслеживать ошибки, которые возникают при отправке запросов. Затем мы создаем функцию handleButtonClick
, которая отправляет GET-запрос на неверный URL и, в случае возникновения ошибки, использует метод setError
для обновления состояния error
с сообщением об ошибке.
Возвращаемое значение компонента содержит кнопку и блок данных. Кнопка вызывает функцию handleButtonClick
, а блок отображается только в том случае, если error
не является нулевым или ложным. В блоке мы выводим сообщение об ошибке, используя свойство message
объекта ошибки.
Шаг 3. Проверим результат работы компонента. Он представлен на картинке ниже.
Кроме того, рассматриваемая библиотека также предоставляет статический метод isCancel()
, который может быть использован для проверки, является ли ошибка результатом отмены запроса. Это может быть полезно, если вы используете CancelToken
или AbortController
для отмены запроса. Об этом мы поговорим немного позже.
Создание базового экземпляра
Базовый экземпляр — это объект, который содержит конфигурационные параметры и методы для создания запросов.
Чтобы организовать базовый экземпляр необходимо использовать create()
из рассматриваемой библиотеки и передать ей объект с настройками. В объекте настроек можно указать общий URL для всех запросов, заголовки, авторизационный токен и другие параметры.
Например, если в приложении нужно отправлять запросы к API с общим адресом ресурса, можно создать базовый экземпляр в директории src
следующим образом.
Шаг 1. Создадим файл с расширением .js
:
nano basic.js
Шаг 2. Далее напишем код:
import axios from 'axios';const exemplar = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com/',
});
export default exemplar;
Шаг 3. Импортирование экземпляра рассмотрим на примере из раздела «Обработка ошибок»:
import React, { useState } from "react";
import axios from "axios";
import exemplar from "./basic";const Test1 = () => {
const [error, setError] = useState(null);
const handleButtonClick = () => {
exemplar
.get("invalid-url")
.then((response) => {
console.log(response);
})
.catch((error) => {
setError(error);
});
};
...
export default Test1;
Изменения — в строках:
exemplar
.get("invalid-url")
и
import exemplar from "./basic";
Использование async и await
Async и Await — это инструменты для управления асинхронными операциями в JavaScript. Они могут значительно упростить код, связанный с обработкой ответов на запросы с помощью Axios в React.
Для использования данных инструментов вам нужно сначала определить функцию, которая будет вызываться асинхронно. Затем вы можете использовать ключевое слово await
, чтобы вызвать функцию Axios и дождаться, пока она выполнит запрос.
Перепишем код из раздела про GET-запрос:
import React, { useEffect, useState } from "react";
import axios from "axios";function Test1() {
const [data, setData] = useState([]);
useEffect(() => {
async function asyncFunction() {
try {
const response = await axios.get("https://jsonplaceholder.typicode.com/users");
setData(response.data);
} catch (error) {
console.log(error);
}
}
asyncFunction();
}, []);
return (
<div>
<h1>Список пользователей:</h1>
<ul>
{data.map((user) => (
<li key={user.id}>
{user.name} ({user.email})
</li>
))}
</ul>
</div>
);
}
export default Test1;
Создается асинхронная функция asyncFunction
, которая ожидает ответа от сервера с помощью ключевого слова await
и устанавливает полученные данные с помощью setData
.
Использование инструментов, описанных в данной главе, позволит пользователям избегать использования колбэков или цепочек then
, что делает код более читабельным и понятным. Важно не забывать, что они также требуют наличие обработки ошибок, которая поможет избежать проблемы с блокировкой потока выполнения и неожиданного поведения программы.
Отмена запросов
В приложениях, которые используют Axios для выполнения запросов, может возникнуть необходимость отменять их во время выполнения.
Вот несколько примеров, когда это может потребоваться:
- Пользователь нажимает на кнопку «Отмена» во время запроса на сервер, потому что он больше не хочет ждать ответа или перешел на другую страницу.
- В приложении произошла ошибка, и запрос больше не нужен.
- Пользователь начал вводить новый запрос, и старый запрос должен быть отменен, чтобы избежать перегрузки сервера запросами.
- Приложение делает несколько последовательных запросов на сервер, и каждый запрос зависит от предыдущего. Если один из таких запросов завершится с ошибкой, следующие запросы могут стать бесполезными и могут быть отменены, чтобы сократить нагрузку на сервер.
Актуальный способ отмены запросов — использование стандартного API AbortController
, который был добавлен в браузеры в ECMAScript 2017. Этот API предоставляет удобный механизм для отмены любых асинхронных операций, включая запросы на сервер.
Чтобы использовать AbortController
, необходимо создать экземпляр с таким же именем и передать его в качестве параметра запроса. Для этого используется метод signal
.
Создадим экземпляр и объявим его сигнал:
const controller = new AbortController();
const signal = controller.signal;
А затем передадим его в параметры запроса:
axios.get('/user', { signal })
.then((response) => {
console.log(response.data);
})
А также добавим функцию уведомления об отмене:
if (axios.isCancel(error)) {
console.log('Запрос отменен', error.message);
}
Чтобы отменить запрос, необходимо вызвать метод abort()
на экземпляре. Добавим его в конец кода:
controller.abort();
Использование стандартного API AbortController для отмены запросов вместо CancelToken
является более простым и естественным способом, поскольку он уже является стандартным API для отмены асинхронных операций в браузере. Это может также упростить поддержку и совместимость кода с другими библиотеками и фреймворками, которые также используют данный способ.
Оптимизация производительности при использования Axios
В этой главе мы рассмотрим несколько советов по оптимизации производительности при использовании Axios в вашем проекте:
- Кэширование запросов
Часто возникает ситуация, когда мы отправляем один и тот же запрос несколько раз в течение короткого времени. В этом случае, мы можем использовать кэширование запросов, чтобы избежать отправки одного и того же запроса несколько раз. Для этого мы можем использовать библиотеку
axios-cache-adapter
или написать свой кэширующий обработчик.
- Минимизация числа запросов
Иногда мы можем получить все необходимые данные с сервера в одном запросе, вместо того, чтобы отправлять несколько запросов на получение разных данных. Например, мы можем объединить несколько запросов в один и получить все необходимые данные с сервера.
- Отмена запросов
Как мы уже упоминали, отмена запросов может быть полезной, когда мы отправляем много запросов или когда пользователь быстро переключается между страницами. Неотмененные запросы могут привести к перегрузке сервера и замедлению производительности приложения.
- Отложенная загрузка данных
В некоторых случаях мы можем отложить загрузку данных до тех пор, пока они не понадобятся пользователю. Например, мы можем загружать данные только когда пользователь прокручивает страницу или открывает модальное окно. Это может уменьшить количество запросов и ускорить производительность приложения.
- Использование интерсепторов
Интерсепторы позволяют нам манипулировать запросами и ответами, перед тем как они будут отправлены или обработаны. Мы можем использовать их для логирования запросов и ответов, обработки ошибок и т.д. Однако, использование слишком большого количества интерсепторов может снизить производительность приложения.
- Использование мемоизации
Возможно использовать библиотеки мемоизации, такие как
React.memo
илиuseMemo
, чтобы избежать повторного рендеринга компонентов, которые не изменились. Это может сократить число запросов к серверу и повысить производительность.
Заключение
Axios — это библиотека для отправки HTTP-запросов, которая может быть использована с React. В этой статье мы рассмотрели основы использования 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!