I'm using ReactJs & AXIOS in this project and i want to make a global error handler without passing by everywhere the request to add catch to it. I've a service gathering all the requests and I'm creating a new instance of it and use it
import Axios from 'axios';
import { getSiteId } from '../helpers';
export class BaseService {
baseRoute;
promise;
constructor() {
let siteUrl = (process.env && process.env.REACT_APP_API_URL) || '';
this.baseRoute = `${siteUrl}/api/v1`;
}
async create(item) {
return await Axios.post(`${this.generateURL()}/`, item, {
...this.configuration,
})
.catch(error => {
return this.errors(error);
});
}
async update(item, id) {
return await Axios.patch(`${this.generateURL(id)}`, item, {
...this.configuration,
});
}
async filter(query) {
return await Axios.get(`${this.generateURL()}`, {
...this.configuration,
params: query,
});
}
creating a new instance like so
let service= serviceFactory.getInstance();
Then access any function
how to do a global handler adding.catch to every request and render component for example modal from global place, and not to pass to every place i use the functions at
You could use Axios.create()
method. An example from the official documentation.
export const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
Now you can export it to use anywhere like this.
import { instance } from './service'
OR with Common JS
const { instance } = require('./service')
Have you checked, error boundry in react. That wrapper component can be wrppaed your whole component and catch any uncatched jS error/exections ans show any fallback UI.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.