簡體   English   中英

被拒絕的 HTTP 承諾沒有命中 catch 塊

[英]rejected HTTP promise doesn't hit catch block

我使用 VueJs(和 Vuex)和 Axios 與 Express Api 進行通信。 我可以刪除自己使用服務的用戶帳戶

import api from '@/services/api.js';

export default {
  deleteAccount: () => api().delete('/users')
};

其中apiaxios實例。 我不需要傳入用戶 ID,因為 api 通過token標識用戶。

在我的設置視圖中,我可以使用此服務

<script>
import { mapActions } from 'vuex';

import UserService from '@/services/users'; 

export default {
  name: 'Settings',
  methods: {
    ...mapActions('alert', [
      'showSuccessAlert',
      'showErrorAlert'
    ])
    deleteAccount: async function() {
      try {
        await UserService.deleteAccount();

        this.showSuccessAlert({ message: 'Account was deleted successfully' });
        // other stuff
      } catch (error) {
        this.showErrorAlert({ message: error.message });
      }
    }
  }
};
</script>

調用UserService.deleteAccount()返回一個掛起的承諾。 使用await返回 api 響應。

目前 api 總是返回500用於測試目的。 我想,如果 Promise 被拒絕,代碼總是會直接跳到 catch 塊中。 在這里,代碼返回一個被拒絕的 Promise(並將“內部服務器錯誤”寫入控制台,但通過並顯示成功警報/從不執行 catch 塊中的代碼。

代碼有什么問題? 我誤解了承諾嗎?


更新

我的 axios 實例

import axios from 'axios';

import TokensService from '@/services/tokens.js';
import store from '@/store/store.js';

function getTokenString() {
  return `Bearer ${TokensService.getToken()}`;
}

export default () => {
  const instance = axios.create({
    baseURL: 'http://localhost:3000/',
    headers: {
      'Content-Type': 'application/json',
      Authorization: getTokenString(),
    },
  });

  instance.interceptors.request.use((config) => {
    config.headers.Authorization = getTokenString();
    return config;
  }, (err) => Promise.reject(err));

  instance.interceptors.response.use((res) => res, (err) => {
    if (err.response.status === 401) {
      store.dispatch('authentication/destroySession');
      store.dispatch('alert/showErrorAlert', { message: err.message });
    }

    return err;
  });

  return instance;
};

調用api().delete()axios.delete('http://localhost:3000/users')

嘗試在這里返回一個被拒絕的承諾

  instance.interceptors.response.use((res) => res, (err) => {
    if (err.response.status === 401) {
      store.dispatch('authentication/destroySession');
      store.dispatch('alert/showErrorAlert', { message: err.message });
    }

    return Promise.reject(err);
  });

根據示例https://github.com/axios/axios#interceptors

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM