how to handle common error pages in react and axios?

Nima hkh
Nima hkh
Aug 3, 2019 · 2 min read
Image for post
Image for post

in our project , we had a problem to control common error pages using axios and show proper error pages like 404 or maintenance mode pages.

in our user flow designs , react has to show the user , a maintenance page or some other error pages when responses status codes are 503 or etc.
after some searches with my friend , we found that axios has an interceptor .

You can intercept requests or responses before they are handled by then or catch. axios

but we had a problem implementing that in our project, we have 40 requests and it’s not very rational to edit all of services to handle error and change router .

so then i use react HOC technique to handle this problem , so my solution is something like this :

import React, {useEffect} from "react";
import axios from "axios";

const checkRequests= Wrapped => {
function CheckRequests(props) {
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
switch (error.response.status) {
case 503 :
props.history.push('/503') //we will redirect user into 503 page
default :
// Do something with response error
return Promise.reject(error);

return (
<Wrapped {...props} />
return CheckRequests

export default checkRequests

and then i use it in my app js:

import React from "react"
import CheckRequests from "./HOC/CheckRequests"

function App(props){ ... }

export default checkRequests(App)

so in every request that has been called from axios , error handling will work .

it was my solution . I like to use yours to .

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store