Skip to content

Docs lacks on error handling: How handle errors with Busboy? #234

@cesco69

Description

@cesco69

I need to catch all error into on file event of busboy and pass the error to next() function.

I want also catch all busboy error and pass the error to next function.

    import * as Busboy from 'busboy';
    
    uploadAction(req: Request, res: Response, next: NextFunction) {
        let busboy: busboy.Busboy;
        // Create a new busboy instance
        // from doc, busboy constructor can raise an exception
        try {
            busboy = new Busboy({ headers: req.headers });
        } catch (err) {
            return next(err);
        } 
               
        busboy.on('file', (fieldname, file, filename) => {
            try {
                // my logic here...  
                throw new Error('Foo');  
            } catch (error) {
                // emit error to standard busboy event
                busboy.emit('error', error);
            }   
        });

        // listen all busboy error
        busboy.on('error', (err: string) => { 
            // remove busboy pipe
            req.unpipe(busboy);
            
            // ???????????????????????????????????
            // copy from https://github.com/expressjs/multer/blob/master/lib/make-middleware.js#L50
            req.on('readable', req.read.bind(req));
            busboy.removeAllListeners();

            // send error to next function
            next(err);
        });

        req.pipe(busboy);
    }

the next function is a global error handler that elaborate the error and send a response, eg.:

    app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
        // some logic here...
        res.send({ error: error.message });
    });

Now, whitout the line

    req.on('readable', req.read.bind(req));

into:

    busboy.on('error', (err: string) => { 
        // remove busboy pipe
        req.unpipe(busboy);
            
        // ???????????????????????????????????
        // copy from https://github.com/expressjs/multer/blob/master/lib/make-middleware.js#L45
        req.on('readable', req.read.bind(req));
        busboy.removeAllListeners();

        // send error to next function
        next(err);
    });

the error handler can't send the response to the client..

But what is the purpose of:

    req.on('readable', req.read.bind(req));

In general: how handle correctly busboy error?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions