无法响应从快递发送的自定义错误消息

这个问题让我很烦恼,因为我知道这跟我没有正确地理解这个问题有关 – 尽pipe花费了几个小时的时间阅读和尝试不同的东西,但是却很难find答案。

我的问题是这样的,我注册时将用户保存到mongodb数据库,我的模式不允许重复的电子邮件,并发送给我一个错误。 我能够控制台loginterminal中的错误,但我有问题发送回客户端。 或者我遇到了问题,如果它回来,我不太确定在哪两个步骤我失去了访问错误消息。

这是我的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')并访问该string。

谢谢

更新

所以我只是通过发邮件来检查邮递员,这可能会导致错误,我得到正确的答复发送。

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

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

邮差反应机构看起来像这样:

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

所以我只是没有正确处理,在我的客户端代码,但仍然在亏损。

谢谢大家,我能find我的问题的答案,所以我张贴在这里,希望它可以帮助别人。

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

当我在客户端上使用catch调用并logging错误时,我期待看到错误中包含的所有内容。 事实certificate,错误返回一个response属性error.response ,这就是所有的消息。

所以改变我的追捕电话:

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

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

 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…} 

我仍然期望能够通过logging错误来看到我能够访问那个“响应”属性,所以如果有人对此有所了解的话,那么包含在评论中将是非常好的。