I'm using formidable for uploading files. When the upload fails (e.g., when the uploadDir is not writable) the error is not handled by form.on('error'), instead it's an uncaught exception. How do I handle upload errors? This is basically the sample code from fromidable's Readme, with a non-existing uploadDir and an error handler.
var formidable = require('formidable'),
http = require('http'),
util = require('util');
http.createServer(function(req, res) {
if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
// parse a file upload
var form = new formidable.IncomingForm();
form.uploadDir = '/foo/'; // this does not exist
form.on('error', function(error) { // I thought this would handle the upload error
console.log("ERROR " + error);
return;
})
form.parse(req, function(err, fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
res.end(util.inspect({fields: fields, files: files}));
});
return;
}
// show a file upload form
res.writeHead(200, {'content-type': 'text/html'});
res.end(
'<form action="/upload" enctype="multipart/form-data" method="post">'+
'<input type="text" name="title"><br>'+
'<input type="file" name="upload" multiple="multiple"><br>'+
'<input type="submit" value="Upload">'+
'</form>'
);
}).listen(8000);
The error I receive is:
events.js:66
throw arguments[1]; // Unhandled 'error' event
^
Error: ENOENT, open '/foo/9b4121c196dcf3f55be4c8465f949d5b'
From what I've seen in Formidable's lib/file.js
, it tries to open the file as a fs.WriteStream
, but never attaches an error
event handler on that stream. When the WriteStream
fails to open the file, it emits an error
event, which is not handled in Formidable and throws an error. I'd say this is a bug in Formidable, as the File
wrapper defined in that file is itself an EventEmitter
, and could intercept errors on the stream and re-emit them as its own error events for upstream handling.