IT이야기

공리 오류를 전체적으로 또는 한 지점에서 관리하는 방법

cyworld 2022. 5. 9. 22:02
반응형

공리 오류를 전체적으로 또는 한 지점에서 관리하는 방법

그때 표준/캐치 액시코드를 앱 전체에 가지고 있는데, 간단한 것이 이렇게 된다.

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

위와 관련된 문제는 내가 그 문제를 복제해야 한다는 것이다.catch()내 앱에서 호출되는 잠재적인 오류를 처리하기 위해 차단하고 내 질문은, 어디에서나 캐치를 사용하는 것이 아니라 진입 지점에서 전 세계적으로 오류를 포착하기 위해 할 수 있는 일이 있는지입니다.

내 앱은 vue로 구축되어 있기 때문에 axi 측 또는 vue에서 솔루션을 찾고 있다.

는 요격기를 사용해야 한다.

먼저 를 사용하여 공리 인스턴스를 생성하십시오.create방법의이것은 당신이 참조하는 대신 당신의 앱 전체에서 사용해야 하는 것이다.axios단도직접의이렇게 보일 것이다.

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

그런 다음 각 해당 인스턴스에 대한 요청에 대한 응답 후에 호출할 공리 인스턴스에 인터셉터를 첨부하십시오.

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

경우에 따라 인터셉터 내부의 오류를 전체적으로 처리하는 것만이 가능하지만, 오류를 전체적으로 처리해야 하는지에 대해 더 많은 제어를 원할 때가 있다.

나는 개인적으로 오류를 범위로 작성하고 핸들러를 로컬로 호출한다.이 접근법으로, 나는 경우에 따라 오류를 범세계적으로 처리하지 않기로 결정할 수 있다.나 또한 특정 조건이 충족되어야만 글로벌 핸들러를 호출하기로 결정할 수 있다.

아래는 글로벌하게 구성된 오류 처리기의 간단한 구현이다.이 기술을 더 잘 이해하기 위해 이 기사(아약스 오류 처리기에 대한 짧은 이야기)를 확인하십시오.

import axios from 'axios';
import {notifier} from './util';

// errorComposer will compose a handleGlobally function
const errorComposer = (error) => {
    return () => {
        const statusCode = error.response ? error.response.status : null;
        if (statusCode === 404) {
            notifier.error('The requested resource does not exist or has been deleted')
        }

        if (statusCode === 401) {
            notifier.error('Please login to access this resource')
        }
    }
}

axios.interceptors.response.use(undefined, function (error) {
    error.handleGlobally = errorComposer(error);

    return Promise.reject(error);
})


// Fetch some missing information
axios.get('/api/articles/not-found').then(resp => {
    // Do something with article information
}).catch(error => {
    const statusCode = error.response ? error.response.status : null;
    // We will handle locally
    // When it's a 404 error, else handle globally
     if (statusCode === 404) {
        // Do some specific error handling logic for this request
        // For example: show the user a paywall to upgrade their subscription in order to view achieves
    } else {
        error.handleGlobally && error.handleGlobally();
    }
})

// Fetch some missing information
axios.get('/api/users/not-found').then(resp => {
    // Do something with user information
}).catch(error => {
    // We want to handle globally
    error.handleGlobally && error.handleGlobally();
})

Axios Multi API를 사용할 수 있다.API를 생성할 때 설정할 수 있는 간단한 onError 콜백(disclaimer:나는 소포의 작가다.사실 나는 많은 프로젝트에서 바퀴를 다시 발명하는 것에 싫증이 나서 그것을 만들었다.

import { createApiFetcher } from 'axios-multi-api';

const api = createApiFetcher({
    apiUrl: 'https://example.com/api/',
    apiEndpoints: {
      getUserDetails: {
          method: 'get',
          url: '/user-details/get',
      },
    },
    onError(error) {
      console.log('Request has failed', error);
    }
});

const data = api.getUserDetails({ userId: 1 });

참조URL: https://stackoverflow.com/questions/48990632/how-to-manage-axios-errors-globally-or-from-one-point

반응형