故障排除:为什么我的函数没有进入 Try/Catch 块?

问题描述 投票:0回答:1

在使用

Vuex
时,我在向 API 发出 GET 请求的特定部分遇到了问题。尽管知道响应应该是 404 错误,但当这种情况发生在该行时,我的代码似乎没有进入 try-catch 块

var rptReq = await investigacionApi.get(url);

。我什至尝试嵌套两组 try-catch 块,但行为保持不变。

export const getUserByEmail = async ({ commit }, { dni, password }) => {
  var path = `/api/usuarios/dni`;
  try {
    const params = { dni, password };
    const url = `${path}?${new URLSearchParams(params)}`;
    console.log(url)
    try {
      var rptReq = await investigacionApi.get(url);
      console.log(rptReq)
      if (!rptReq || !rptReq.data) {
        throw new Error('La respuesta recibida es inválida');
      }
      const { status, data } = rptReq.data;
      commit('setUserProvider', { status, data, message: null })
    } catch (errores) {
      const { status, error } = errores.response.data;
      commit('setUserProvider', { status, data: null, message: error })
    }
  } catch (error) {
    console.log(error);
    commit('setUserProvider', { status: false, data: null, message: "error.message" })
  }
}

屏幕截图显示了我的控制台错误,表明我的代码在第 29 行(对应于 API GET 请求)处损坏。然而,当我在 POSTMAN 中测试相同的场景时,我收到了带有正文的 404 响应。

这是我的investigacionApi.js

import axios from 'axios'
const apiUrl = process.env.VUE_APP_API_URL;
const investigacionApi = axios.create({
    baseURL: apiUrl
})

export default investigacionApi
javascript vuejs3 vuex
1个回答
0
投票

我在这里看到问题,实际上

404
不是
error or exception
,而是
status code
。这就是为什么它不会进入
catch block

你可以试试这个

export const getUserByEmail = async ({ commit }, { dni, password }) => {
  var path = `/api/usuarios/dni`;
  try {
    const params = { dni, password };
    const url = `${path}?${new URLSearchParams(params)}`;
    console.log(url)
    try {
      var rptReq = await investigacionApi.get(url);

      // check here for specific scenario from the rptReq.

      console.log(rptReq)
      if (!rptReq || !rptReq.data) {
        throw new Error('La respuesta recibida es inválida');
      }
      const { status, data } = rptReq.data;
      commit('setUserProvider', { status, data, message: null })
    } catch (errores) {
      const { status, error } = errores.response.data;
      commit('setUserProvider', { status, data: null, message: error })
    }
  } catch (error) {
    console.log(error);
    commit('setUserProvider', { status: false, data: null, message: "error.message" })
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.