Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

242
Views
Avoid handling if error has response in Vue with Axios in every request

I use the axios interceptors to handle some errors, specially the errors without response. And in some parts of my project, I use the message contained in the error.response.data for validations and showing a messaged stored in the backend. But this interceptor is not preventing me from having to check if the error has a response.

My interceptor:

axios.interceptors.response.use(
    function (response) {
      ...
    },
    function (error) {
      if (!error.response) {
        ...
        return Promise.reject(new Error(error.message))
      }

An example of a request that depends on having the error.response:

this.$store.dispatch('updateField', { [this.fieldKey]: this.value ? this.value : null }).catch((error) => {
        this.validateField(error.response.data)
      })

But I'd have to put the validateField call inside an if(eror.response) to avoid an error in the console, and spread this if all over my code?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

response can be treated as optional, because it actually is:

this.validateField(error.response?.data)

Or normalized error that contains needed properties and doesn't rely on the structure of Axios error can be created in an interceptor:

function (rawError) {
  const error = new Error(error.response?.data?.myError || error.message);
  error.data = error.response?.data || null;
  error.headers = error.response?.headers || null;
  error.status = error.response?.status || 0;
  return Promise.reject(error);
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!