programing

약속을 어기다

javaba 2022. 8. 14. 17:58
반응형

약속을 어기다

안녕하세요. 제 질문이 제대로 구체화되지 않았다면 죄송합니다.

글로벌 함수에서 axios js의 약속을 정의하고 싶습니다.여기서 401 상태를 글로벌하게 처리/파악하고 사용자를 로그아웃합니다.나는 모든 질문에서 그것을 처리하고 싶지 않다.

요청을 처리하기 위한 소스 글로벌 함수:

export function requestData (url, payload = {}) {
  return axios.post(url, payload)
    .then(response => {
      return response.data
    })
    .catch(error => {
      if (error.response.status === 401) {
        logout()
      } else {
        return error
      }
    })
}

컨트롤러에서 사용하는 기능의 예를 다음에 나타냅니다.

requestData('/api/persons', {options: this.options, search: search})
  .then(data => {
    this.data = data
  })
  .catch(error => {
    this.error = error.toString()
  })

문제는 컨트롤러의 약속 캐치가 예외가 있을 때 실행되지 않는다는 것입니다.어떻게 하면 알 수 있을까요?

바꾸다return error당신의 안에서requestData기능하다throw error

Axios 문서에 따르면

요청 또는 응답이 처리되기 전에 대행 수신하거나 수신할 수 있습니다.

응답 가로채기를 사용하려고 합니다.

axios.interceptors.response.use(function(response) {
  // Do something with response data
  return response;
}, function(error) {
  // Do something with response error
  if (error.status === 401) {
    logout()
  }
  return Promise.reject(error);
});

교환return error타고throw error반쪽짜리 작업입니다.
내가 옳을 때throw errorin promise catch는 다음 promise .disposit 문을 호출하지 않습니다.이것은 .then 문으로 동작합니다.

다음과 같이 동작합니다.

export function requestData (url, payload = {}) {
  return axios.post(url, payload)
    .then(response => {
      return response.data
    })
    .catch(error => {
      if (error.response.status === 401) {
        logout()
      } else {
        return error
      }
    })
   .then(result => {
      if (result instanceof Error) {
        throw result
      } else {
        return result
      }
    })
}

언급URL : https://stackoverflow.com/questions/46979633/pass-error-after-catch-on-promises

반응형