在 Node.js 中用 try..catch 处理错误
Error handling with try..catch in Node.js
我想知道在以下情况下我是否正在以正确的方式处理 错误 以及在 错误时我应该 return 什么?你可以 return statusCode 任何东西或只 response 吗?
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);
}
})
您只能在响应对象上使用状态代码。
有关详细信息,请阅读 this。
尝试阅读此 question 一次。
您的更新代码的答案:
您可以在回调对象中发送错误。
详细了解 callback here。
回调有两个参数:
- 错误
- 数据
我将在下面更新您的代码:
更新代码:
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);
}
})
这就是您使用回调处理错误的理想方式。
试试这个,看看它是否有效。
我想知道在以下情况下我是否正在以正确的方式处理 错误 以及在 错误时我应该 return 什么?你可以 return statusCode 任何东西或只 response 吗?
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);
}
})
您只能在响应对象上使用状态代码。
有关详细信息,请阅读 this。
尝试阅读此 question 一次。
您的更新代码的答案:
您可以在回调对象中发送错误。 详细了解 callback here。
回调有两个参数:
- 错误
- 数据
我将在下面更新您的代码:
更新代码:
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);
}
})
这就是您使用回调处理错误的理想方式。
试试这个,看看它是否有效。