F
F
fessss2020-10-30 19:48:20
Vue.js
fessss, 2020-10-30 19:48:20

Generic error handler for requests in vue?

Let's say there is some component with a bunch of methods that access the api
, I do the error handling through try catch
But it turns out a lot of straight code. Can it be done in some other way? More concise.

methods: {
async func1() {
  try {
    await axios.post(url);
    await axios.get(url);
  }
  catch (e) {
    console.log(e)
  }
},
async func2() {
  try {
    await axios.get(url);
  }
  catch (e) {
    console.log(e)
  }
},
async func3() {
  try {
    await axios.get(url);
  }
  catch (e) {
    console.log(e)
  }
},
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor, 2020-10-30
@fessss

Use an interceptor.
I'll give you my example.
Designed as a plugin for VUE.
Pay attention to this line Now all requests go through the interceptor, it is in it that I will catch and process protocol errors.
export const $axios: AxiosInstance = _axios

import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import Vue from 'vue'

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

/* eslint-disable */
const config = {
  baseURL: process.env.VUE_APP_API,
  timeout: 30000,
  validateStatus (status: number) {
    return status < 500 // Resolve only if the status code is less than 500
  }
}
/* eslint-enable */

const _axios: AxiosInstance = axios.create(config)

/* eslint-disable */
// @ts-ignore
_axios.interceptors.request.use(async (config: AxiosRequestConfig): AxiosRequestConfig | Promise<AxiosRequestConfig> => {
  return Promise.resolve(config)
  },  (error) => {
    // Do something with request error
    return Promise.reject(error)
  }
)
/* eslint-disable */

// Add a response interceptor
_axios.interceptors.response.use((response): Promise<AxiosResponse> | any => {
  return response
  },  (error) => {
    // Do something with response error
    return Promise.reject(error)
  }
)

class AxiosPlugin {
  public install () {
    Object.defineProperties(Vue.prototype, {
      axios: {
        get () {
          return _axios
        }
      },
      $axios: {
        get () {
          return _axios
        }
      }
    })
  }
}

const axiosPlugin: AxiosPlugin = new AxiosPlugin()

Vue.use(axiosPlugin)

export default axiosPlugin
export const $axios: AxiosInstance = _axios

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question