PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 14, 2022

[FIXED] How to manage axios errors globally or from one point

 October 14, 2022     axios, javascript, promise, try-catch, vuejs2     No comments   

Issue

I have the standard then/catch axios code all over my app, a simple one goes likes this..

axios.get('/').then( r => {} ).catch( e => {} )

The problem I have with the above is that I have to duplicate the catch() block to handle any potential errors that my be invoked in my app and my questions is, if there is anything I can do to catch the errors globally from on entry point as opposed to using catch everywhere.

I am looking for solutions from either axios side or vue, since my app is built with vue


Solution

You should use an interceptor.

First, create an axios instance using the create method. This is what you would need to use throughout your app instead of referencing axios directly. It would look something like this:

let api = axios.create({
  baseURL: 'https://example.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

Then attach an interceptor to your axios instance to be called after the response to each of the requests for that instance:

api.interceptors.response.use((response) => response, (error) => {
  // whatever you want to do with the error
  throw error;
});


Answered By - thanksd
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing