mogul
mogul

Reputation: 4553

Handling errors in express pipelines

I have a small web service that basically receives a PUT and saves the payload to a file. It can happen that the file write fails due to permission issues. I would like that to be communicated back to the client.

To make it easier to read I have boiled the program down to a minimum. The req.pipe chain is way longer in the real program. (with many more possibilities for errors)

const fs = require('fs');
const express = require('express');
const app = express();

app.put('/write/:id', (req, res, next) => {
    const filename = 'data/' + req.params.id;
    console.log("write: " + filename);

    req 
        .pipe(fs.createWriteStream(filename))
        .on('error', next)
        
    req.on('end', () => {
        res.send('saved\n' );
        console.log("sent response");
    })
});

app.listen(8081, '0.0.0.0');

Trouble is that no matter what I do it will always respond "saved" to the client. I had kinda hoped the next call would have got me out of there.

What is the elegant way to make differentiated responses on errors occurring server side?

Upvotes: 1

Views: 97

Answers (1)

mogul
mogul

Reputation: 4553

several hours later it seems I nailed it:

const fs = require('fs');
const express = require('express');
const app = express();

app.put('/write/:id', (req, res, next) => {
    const filename = 'data/' + req.params.id;
    console.log("write: " + filename);

    req 
        .pipe(fs.createWriteStream(filename))

        .on('error', (e) => {
            console.log("error ", e);
            res.status(400).send("failed");
        })
        
        .on('close', () => {
            res.send("saved\n");
        })      
});

app.listen(8081, '0.0.0.0');

Notice how I'm listening for close within the pipeline and not end on the request it self.

Upvotes: 1

Related Questions