res.json is not sending my error message to the client?

╄→гoц情女王★ 提交于 2020-06-29 04:45:09

问题


I have this error handler that retreives specific error messages based on what happens. But the thing is when I run my error handler function with .catch() it will work if i'm logging to the node console, but when i try send it to the client via res.json() it will only send the status code, not any part of my error handler.

function errorHandler(error){
  if (error.name === 'SequelizeValidationError') {
    const errors = error.errors.map(err => err.message);
    return errors;
  } else {
    throw error;
  }
}


router.post('/create', async(req, res) => {
     await Movie.create(req.body)
      .then(() => res.json("Movie Created"))
      .catch( err => res.status(401).json(errorHandler(err)) );
  });

This is my code for the error handler and the route i'm talking about. It works in the node console, but like I said it only sends the status 401 code to the client and nothing else. How can I get my error message send to the client as well?

Thank you!


回答1:


Because its not waiting for result from errorHandler. Make them wait for it. Try this.

function errorHandler(error, cb){
  if (error.name === 'SequelizeValidationError') {
    const errors = error.errors.map(err => err.message);
     cb(errors);
  } else {
    throw error;
  }
}


router.post('/create', async(req, res) => {
     await Movie.create(req.body)
      .then(() => res.json("Movie Created"))
      .catch( err => {
              errorHandler(err, function(errors){
                   res.status(401).json(errors);
               });
      });
  })

Or you can return a Promise and await on errorHandler.



来源:https://stackoverflow.com/questions/62491396/res-json-is-not-sending-my-error-message-to-the-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!