我想捕获所有可能在文件上传上引发的严重错误。到目前为止,我在最基本的方法上失败了:文件夹不存在。请注意,仅通过为要保存的文件添加不存在的路径来生成此错误以进行测试。代码本身可以正常工作,而不会产生错误。
以下是我尝试过的过度/垃圾邮件尝试/捕获示例:
router.post('*', (req, res) => {
try {
// path is formed based on the type of file to be uploaded.
// the file type is sent to different path. Ex.: logo: upload/logo
const folder = path.join(__dirname, '../../public-NOT-EXISTING/media' + req.url);
// check if folder exist, if not, create it
// if (!fs.existsSync(folder)) {
// fs.mkdirSync(folder);
// console.log(util.yellow, 'Folder was created', util.Reset);
// }
// console.log(util.green,'Uploading to folder:', folder, util.Reset);
const form = new formidable.IncomingForm();
form.keepExtensions = true;
form.uploadDir = folder;
form.maxFieldsSize = 20 * 1024 * 1024;
//Emitted whenever a new file is detected in the upload stream. Use this event if you want to stream the file to somewhere else while buffering the upload on the file system.
/* this is where the renaming happens */
form.on('fileBegin', function (name, file) {
//rename the incoming file to the file's name
file.path = form.uploadDir + file.name;
});
//Emitted whenever a field / file pair has been received. file is an instance of File.
form.on('file', function(name, file) {
console.log(util.magenta, 'Uploaded file name:', name, '(current name:', file.name,"')", util.Reset);
res.status(200).send({message: 'File Uploaded'})
});
//Emitted when there is an error processing the incoming form. A request that experiences an error is automatically paused, you will have to manually call request.resume() if you want the request to continue firing 'data' events.
form.on('error', function(err) {
console.error('Something went wrong in uploading file:', err);
res.status(500).send({message: err})
});
function errorHandle(err){
console.error('Got the error in function cb', err);
}
form.parse(req, (errorHandle, fields, files) => {
if (errorHandle)
console.error('Got the error as CB argument', errorHandle);
try{
console.log('\n parsing uploaded file -----------');
console.log('Fields', fields);
console.log('Received:', Object.keys(files));
console.log();
}catch (e) {
console.error('Got the error in "parse" function', e)
}
});
}catch (e) {
console.error('Got the error in general try/cath', e)
}
});
但是,什么都没有捕获到错误并且服务器崩溃了:
Error: ENOENT: no such file or directory, open 'D:.... my path...'
Emitted 'error' event at:
at fs.open (internal/fs/streams.js:279:12)
at FSReqCallback.args [as oncomplete] (fs.js:145:20)
[nodemon] app crashed - waiting for file changes before starting...
答案 0 :(得分:0)
尝试一下:
process.on('uncaughtException', function(err) {
// you can get all uncaught exception here.
console.log(err)
})
答案 1 :(得分:0)
// Error Handlers
process.on('unhandledRejection', async err => {
console.error('Unhandled rejection', JSON.stringify(err));
});
process.on('uncaughtException', async err => {
console.error('Uncaught exception', JSON.stringify(err));
});