【问题标题】:Error handling with try..catch in Node.js在 Node.js 中使用 try..catch 处理错误
【发布时间】:2018-10-29 17:40:35
【问题描述】:

我想知道在以下情况下我是否以正确的方式处理 error 以及我应该在 error 时返回什么?您可以在任何内容上或仅在响应上返回 statusCode 吗?

const storage = multer.diskStorage({
destination: function (req, file, cb) {
    if (err) {
        new Error({
            status: "INTERNAL SERVER ERROR"
        })
    }
    let filepath = './public/images/'
    cb(null, filepath)
},
filename: function (req, file, cb) {
    if (err) {
        new Error({
            status: "INTERNAL SERVER ERROR"
        })
    }
    let ext = file.originalname.split(".").pop();
    let filename = file.fieldname + '-' + Date.now() + '.' + ext
    //console.log(ext);
    cb(null, filename);
}

})

【问题讨论】:

标签: node.js error-handling callback response http-status-codes


【解决方案1】:

您只能在响应对象上使用状态代码。

更多详情请阅读this

尝试阅读此question 一次。


更新代码的答案:

您可以在回调对象中发送错误。 阅读有关callback here 的更多信息。

回调有两个参数:

  1. 错误
  2. 数据

我会在下面更新你的代码:

更新代码:

    const storage = multer.diskStorage({
        destination: function(req, file, cb) {
            if (err) {
                cb(err, null);
            }
            let filepath = './public/images/'
            cb(null, filepath)
        },
        filename: function(req, file, cb) {
            if (err) {
                cb(err, null);
            }
            let ext = file.originalname.split(".").pop();
            let filename = file.fieldname + '-' + Date.now() + '.' + ext
            //console.log(ext);
            cb(null, filename);
        }
    })

这是您使用回调处理错误的理想方式。

试试这个并检查它是否有效。

【讨论】:

  • 我根据这些答案编辑了我的代码。这是现在还是在这种情况下我需要处理?
  • 好的,告诉我,你有传入的 req 对象,对吗?那么你必须为那个 req 对象拥有 res 对象。您可以在 cb 中发送错误,而不是创建“新错误....”,如果您能回答我的上述问题,我会更新我的答案
  • 我会在答案中更新你的代码,检查一下。
猜你喜欢
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-03
  • 2022-01-24
相关资源
最近更新 更多