简体   繁体   English

节点正确返回错误(例如,验证错误)

[英]Node return errors correctly (e.g. validation errors)

I'm refactoring our code into promises. 我正在将我们的代码重构为Promise。

Two blocks with sample code: 两个带有示例代码的块:

user.service.js user.service.js

export function updateUserProfileByUsername(req, res) {
userController.getUserByUsername(req.params.username)
    .then((userProfile) => {
        return userController.saveUserProfileByUser(userProfile,
            req.body.email,
            req.body.username,
            req.body.firstname,
            req.body.lastname)
    })
    .then((updated_user) => {
        res.status(200).json(updated_user.profile);
    })
    .catch((err) => {
        res.status(404).send('something went wrong');
    });
}

export function getUserProfileByUsername(req, res) {
userController.getUserProfileByUsername(req.params.username)
    .then((userProfile) => {
        res.status(200).json(userProfile);
    })
    .catch((err) => {
        res.status(404).send('something went wrong');
    })
}

user.controller.js user.controller.js

export function getUserProfileByUsername(username) {
return User.findOne({
        'username': username
    }).exec()
    .then((user) => {
        if (user)
            return user.profile;
        else
            throw new Error("user not found!");
    });
}

export function getUserByUsername(username) {
return User.findOne({
        'username': username
    }).exec()
    .then((user) => {
        if (user)
            return user;
        else
            throw new Error("user not found!");
    });
}

export function saveUserProfileByUser(user, email, username, firstname, lastname) {
  user.email = email;
  user.username = username;
  user.firstname = firstname;
  user.lastname = lastname;
  return user.save(); // returns a promise
}

Our routes enter in user/index.js, go into service.js and the controller handles our database work and errors. 我们的路线输入到user / index.js,进入service.js,控制器处理我们的数据库工作和错误。

What I am trying to achieve is to send fitting errors to the client. 我要实现的目标是向客户发送拟合错误。 Like: 'the user does not exist' or 'username is too long' when updating a wrong user, etc. 例如:更新错误的用户等时,“用户不存在”或“用户名太长”。

if I try to send the error to the client, i'll just get a empty json as result ({}). 如果我尝试将错误发送给客户端,我将得到一个空的json作为结果({})。 If I log the error, i get the full stack trace, including validation errors. 如果我记录错误,我会得到完整的堆栈跟踪信息,包括验证错误。

.catch((err) => {
        console.log(err) // shows me full stacktrace of the error
        res.status(404).send(err); //sends {} to the client
    })

How can I implement this with promises? 我如何实现承诺? Should i add extra middleware sending correct error messages? 我应该添加额外的中间件来发送正确的错误消息吗?

I would really appreciate some hints in the right direction for this one. 我真的很感谢在此方向上的一些提示。 Thanks in advance! 提前致谢!

Because err is an object I assume express is converting to JSON for you. 因为err是一个对象,所以我认为express将为您转换为JSON。 However, when you stringify an error you get '{}'; 但是,当您对错误进行字符串化处理时,会得到“ {}”;

If you want to return the stacktrace try .send(err.stack). 如果要返回堆栈跟踪,请尝试.send(err.stack)。

Alternatively if you only want the message and not the entire stack you can use err.message. 或者,如果您只想要消息而不是整个堆栈,则可以使用err.message。

.catch((err) => {
    console.log(err)
    res.status(404).send(err.stack);
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果节点属性与 function 混淆,如何突出显示错误,反之亦然。 例如,显示 `node.innerText()` 或 `node.toLowerCase` 的错误 - How to highlight error if a node property is confused with function and vise versa. e.g. Show errors for `node.innerText()` or `node.toLowerCase` Node/Express:为什么不能将 res 传递给帮助程序 function(例如用于验证)并避免 ERR_HTTP_HEADERS_SENT? - Node/Express: Why can't you pass res to a helper function (e.g. for validation) and avoid ERR_HTTP_HEADERS_SENT? aurelia-validation:验证错误未正确显示 - aurelia-validation: validation errors are not shown correctly jQuery无法正确跟踪验证错误 - jQuery not keeping track of validation errors correctly 来自 SCSS 的 Flexbox 在 Firefox 上正常工作,但在其他浏览器(例如 Chrome、Edge 等)上不能正常工作 - Flexbox from SCSS working correctly on Firefox but not on other browsers (e.g. Chrome, Edge, …) 如何使用另一个属性返回特定的Geojson要素属性,例如按名称返回经度属性? - How to return specific Geojson feature property using another property, e.g. return longitude property by name? 使用外部JS文件捆绑TypeScript(例如node_modules) - Bundle TypeScript with external JS files (e.g. node_modules) 为什么Express模块​​没有安装在其默认目录中,例如npm \\ node_modules? - Why the express module is not installing in its default directory e.g., npm\node_modules? 将是node.js中原始套接字的支持,例如创建ping数据包吗? - Will be a support of raw sockets in node.js, e.g. to create ping packets? 如何调用和打印节点类型名称而不仅仅是数字(例如:“ELEMENT_NODE”)? - How to call and print nodeType name instead of just the number (e.g.: "ELEMENT_NODE")?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM