javascript - 无法响应从 express 发送的自定义错误消息

标签 javascript node.js express

这个问题让我很烦,因为我知道这与我没有正确理解这个问题有关——这使得很难找到答案,尽管我花了几个小时阅读和尝试不同的东西。

我的问题是,我在用户注册时将其保存到 mongodb 数据库,我的架构不允许重复的电子邮件,并向我发回错误消息。我能够在终端中控制台记录错误,但我无法将其发送回客户端。或者我在使用它做某事时遇到问题,如果它再次出现,我不太确定在这两个步骤中的哪个位置我无法访问错误消息。

这是我保存用户的 POST 路由:

router.post('/users', (req, res) => {
  let body = _.pick(req.body, ['email', 'password']);
  let user = new User(body);

  user.save().then(() => { // this all works and will save the user, if there are no errors
    return user.generateAuthToken();
  }).then((token) => {
    res.header('Authorization', `Bearer ${token}`).send(user);
  }).catch((err) => { // This is where my problem is
    console.log(err); // This will log the mongodb error here, about duplicate emails
    res.status(500).send(err); // I'm trying to send the mongodb error message back to the client to display it on the screen (I will handle making the message friendly to read, once I can get this to work)
  });
});

所以我遇到了 mongo 错误,然后我尝试通过将它发送给客户端来响应它。

这是我的客户端代码:

axios({
  method: 'post',
  url: '/auth/users',
  headers: {
    'Content-Type': 'application/json'
  },
  data: {
    email,
    password
  }
}).then((res) => {
  console.log('this is the response', res);
  if (res.status === 200) {
    var authToken = res.headers.authorization.split(' ')[1];
    authenticateUser(authToken);
    this.props.history.replace('/dashboard');
  } // This all works fine for a signup with no errors
}).catch((err) => {
  console.log('Signup error:', err);
  // I am expecting the above line of code to log the long Mongodb 
  // error message that I am sending back in my res.status(500).send(err)
  // catch call from the server, but instead all I am getting is
  // "Signup error: Error: Request failed with status code 500"
});

要么我没有正确发送错误,要么当它返回时我没有正确处理它,但我不知道它是什么或为什么。

我什至无法发回 res.status(500).send('some string here') 并访问该字符串。

谢谢

更新

所以我只是通过发送可能导致错误的 POST 检查了 postman,然后我收到了正确的响应。

我的服务器捕获实际上是这样的:

.catch((err) => {
  res.status(500).send({message: err.message});
});

postman 响应正文如下所示:

{
  "message": "E11000 duplicate key error collection: authBoilerplate.users index: email_1 dup key: { : \"email@example.com\" }"
}

所以我只是没有在我的客户端代码中正确处理它,但仍然不知所措。

最佳答案

谢谢大家,我找到了我的问题的答案,所以我把它贴在这里,希望它能帮助到其他人。

我肯定会发回我的自定义错误消息,我只是没有在客户端正确处理它。

当我在客户端上使用 catch 调用并记录错误时,我希望看到错误中包含的所有内容。事实证明,错误返回时带有 response 属性 error.response,这就是所有消息传递的地方。

因此将我的 catch 调用更改为:

axios(//... send post in here)
.then(// ... same as in my question)
.catch((err) => {
  console.log('error', err);
  console.log('error response', err.response); // this is where the actual error response message is error.response.message
});

导致记录堆栈跟踪和错误响应:

error Error: Request failed with status code 500
    at createError (eval at <anonymous> (bundle.js:541), <anonymous>:16:15)
    at settle (eval at <anonymous> (bundle.js:847), <anonymous>:18:12)
    at XMLHttpRequest.handleLoad (eval at <anonymous> (bundle.js:520), <anonymous>:77:7)
error response Object {data: Object, status: 500, statusText: "Internal Server Error", headers: Object, config: Object…}

我仍然希望能够通过仅记录错误来看到我可以访问该“响应”属性,因此如果有人对此有任何见解,最好将其包含在评论中。

关于javascript - 无法响应从 express 发送的自定义错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44599412/

相关文章:

javascript - 关于在 JavaScript 中制作 NEAT 原型(prototype)的几个问题

mysql - Angular NodeJs multer upload img req.file 始终未定义

node.js - 重定向到登录时出现 Keycloak CORS 问题

node.js - 有或没有 token JWT+PASSPORT 可用的路线

javascript - NodeJS + ExpressJS 压缩什么都不做?

javascript - CSS 仅适用于表格,不适用于表格标题 (th)

javascript - 基本 Javascript 函数中的语法错误

javascript - Twitter Bootstrap 模态通过 Ajax 更改内容

javascript - 从 Twitter 媒体的 URL 读取文件同步 - node.js

javascript - 文件上传和 Google Protobuf