【问题标题】:Getting error message with koa.js + axios使用 koa.js + axios 获取错误消息
【发布时间】:2018-05-15 16:45:53
【问题描述】:

我将koa.js 用于后端,axios 用于前端的http 请求。我想在 koa.js 中设置错误消息并在前端获取错误消息,但我只收到默认错误消息 "Request failed with status code 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);
  }
};

使用 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);
      });
  };
}

【问题讨论】:

    标签: javascript node.js axios koa


    【解决方案1】:

    1) 主要问题 compileOneInterest 函数抛出数组而不是错误对象。在你的截图错误是[{message: 'Sorry, that page does not exist', code: 34}]。你的 try 块正在运行:

    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

    【讨论】:

      猜你喜欢
      • 2020-09-10
      • 2019-07-26
      • 1970-01-01
      • 2020-08-12
      • 2020-07-15
      • 2011-06-27
      • 1970-01-01
      • 1970-01-01
      • 2017-11-27
      相关资源
      最近更新 更多