javascript - 使用 koa.js + axios 获取错误消息

标签 javascript node.js axios koa

我正在使用koa.js用于后端和axios用于前端的http请求。我想在 koa.js 中设置错误消息并在前端获取错误消息,但我只得到默认错误消息“请求失败,状态代码为 500”

koa.js api调用

module.exports.addIntr = async (ctx, next) => {
  const intrObj = ctx.request.body;
  try {
    intrObj = await compileOneInterest(intrObj);
    ctx.response.body = intrObj;
  } catch (err) {
    const statusCode = err.status || 500;
    ctx.throw(statusCode, err.message);
  }
};

enter image description here

使用 axios 进行 http 请求

export function addInter(interObj) {
  return (dispatch) => {
    const url = `${API_ADDRESS}/ep/${10}/intr/`;

    axios({
      method: 'post',
      url,
      data: interObj,
      // params: {
      //   auth: AccessStore.getToken(),
      // },
    })
      .then((response) => {
        dispatch(addIntrSuccess(response.data));
      })
      .catch((error) => {
        dispatch(handlePoiError(error.message));
        console.log(error.response);
        console.log(error.request);
        console.log(error.message);
      });
  };
}

enter image description here

最佳答案

1) 主要问题 compileOneInterest 函数抛出数组而不是 Error 对象。您的屏幕截图中的错误是[{message: '抱歉,该页面不存在', code: 34}]。您的 try block 正在运行:

const statusCode = err.status || 500; // undefined || 500 
ctx.throw(statusCode, err.message); // ctx.throw(500, undefined);

因此您会看到默认消息。

2) 您使用类似错误的对象来代替 new Error('message')CustomError('message', 34)

class CustomError extends Error {
  constructor(message, code) {
    super(message);
    this.code = code;
  }
}

最佳实践是抛出错误或自定义错误对象。

3) 您的 statusCode 计算使用 err.status 而不是 err.code

关于javascript - 使用 koa.js + axios 获取错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47595754/

相关文章:

javascript - Axios 拦截器 : block access to particular pages

node.js - 如何在重新渲染时将数据保留在 react 组件中?

node.js - 使用 axios 处理 JSON 数据时遇到问题

node.js - 使用 Homebrew 程序安装新 Node 后执行 "npm -g update"时出错

mysql - 无法从 Node.js 应用程序连接到 MySQL 数据库

mysql - 如何将sql server连接到app.js文件?

javascript - 如何设置 Essential JS 甘特图一周的第一天

javascript - JS 事件监听器,其函数只有一个参数

javascript - 使用 Ruby Sinatra erb 模板访问 jQuery Mobile (jqm) 多页 html

javascript - 为什么调用这个 javascript 文件?