【问题标题】:Possible to emit error with busboy?可能会与 busboy 一起发出错误?
【发布时间】:2016-11-17 13:09:49
【问题描述】:

是否可以用 busboy 发出错误并处理它?

示例:

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

如果我这样做,我会收到以下错误:

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)

我希望能够通过消息发出我自己的错误,然后在错误事件中删除上传的文件。

【问题讨论】:

    标签: javascript node.js busboy


    【解决方案1】:

    您的代码的问题是使用this 而不是变量busboy

    使用这种方法,事件发射器是您刚刚声明的 函数,而不是 busboy

    这样你就有了一个未处理的“错误”事件,因为没有任何东西在监听函数事件。

    你应该做的是:

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

    只需将this 更改为busboy

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-07
      • 2014-08-11
      • 1970-01-01
      • 1970-01-01
      • 2015-05-27
      • 2019-01-20
      • 2015-12-10
      相关资源
      最近更新 更多