6

Is it possible to emit an error with busboy and handle it?

example:

busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
    if(mimetype !== 'application/pdf') {
        this.emit('error',new Error('Wrong file type'));
        return;
    }
}
busboy.on('error', function(err) {
    console.log('An error has occured: \n' + err);
});

If I do that, I get the following error:

events.js:141
      throw er; // Unhandled 'error' event
      ^

Error: Wrong file type
    at Busboy.<anonymous> (/home/ubuntu/workspace/suploadtest/app.js:44:31)
    at emitMany (events.js:108:13)
    at Busboy.emit (events.js:182:7)
    at Busboy.emit (/home/ubuntu/workspace/uploadtest/node_modules/busboy/lib/main.js:31:35)
    at PartStream.<anonymous> (/home/ubuntu/workspace/uploadtest/node_modules/busboy/lib/types/multipart.js:213:13)
    at emitOne (events.js:77:13)
    at PartStream.emit (events.js:169:7)
    at HeaderParser.<anonymous> (/home/ubuntu/workspace/uploadtest/node_modules/busboy/node_modules/dicer/lib/Dicer.js:51:16)
    at emitOne (events.js:77:13)
    at HeaderParser.emit (events.js:169:7)

I want to be able to emit my own errors with messages and then delete the uploaded files in the error event.

Spark323
  • 1,525
  • 2
  • 16
  • 27

1 Answers1

1

The problem with your code is the use of this instead of the variable busboy.

With this approach the event emitter is the function you just declared and not busboy

That way you have an Unhandled 'error' event because nothing is listening to the function events.

What you should do is the following:

busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
    if(mimetype !== 'application/pdf') {
        busboy.emit('error',new Error('Wrong file type'));
        return;
    }
}

Just change this to busboy

Lucas Fabre
  • 1,806
  • 2
  • 11
  • 25