使用Node.js中的try..catch进行错误处理

时间:2018-05-19 13:02:22

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

我想知道在以下情况下我是否正确处理错误的方式以及我应该在错误上返回什么?您可以在任何内容上或仅在响应上返回 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);
}

})

1 个答案:

答案 0 :(得分:1)

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

有关详细信息,请参阅this

尝试阅读此question一次。

更新代码的答案:

您可以在回调对象中发送错误。 详细了解callback here

回调需要两个参数:

  1. 错误
  2. 数据
  3. 我将在下面更新您的代码:

    更新代码:

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

    这就是理想情况下处理回调错误的方法。

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