Search code examples
javascriptnode.jsaxioskoa

Getting error message with koa.js + axios


I am using koa.js for back-end and axios for http requests in front-end. I want to set up error message in koa.js and get the error message in front-end, but I get only default error message "Request failed with status code 500"

koa.js api call

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

http request with axios

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


Solution

  • 1) Main issue compileOneInterest function throws array instead Error object. On your screenshot err is [{message: 'Sorry, that page does not exist', code: 34}]. Your try block is running:

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

    So you see default message.

    2) You use error-like object instead new Error('message') or CustomError('message', 34)

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

    Best practise is throw Errors or custom Error object.

    3) Your statusCode calculation use err.status instead err.code.