loading...

how to handle common error pages in react and axios?

nimahkh profile image Nima Habibkhoda ・1 min read

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) {
        useEffect(()=>{
            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 
                        break
                    default :
                        break
                }
                // 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 .

Posted on by:

nimahkh profile

Nima Habibkhoda

@nimahkh

#react #laravel #node.js

Discussion

markdown guide
 

I had the same problem in my last project. But it was about 10 routes and i've solved it with one self written function. It was smth like:
if(err) window.location = neededErrPage

 

your solution is very good if you had some services , but my services are so much and it was not a good solution ,
what if , i had to change the route again , or something was wrong in my code ? i had to change 40 routes again ,
thank you bro

 

Of course this solution is well for mini projects. U r welcome)

 

This Solution is not working for me