Wednesday 17 May 2017

How to handle an error from a stream that you're piping as an HTTP response?

Here is a gist with both the server/client code, but I'll post the server code here as well:const Router = require('koa-router'); const fs = require('fs'); const generateFile = require('./generateFile'); const router = new Router(); router.post('/getFile', async (ctx) => { const filePath = generatePDF(ctx.request.body); const rs = fs.createReadStream(filePath); // This might throw an error rs.on('error', (err) => { ctx.response.status = 500 // This isn't working. The status code of 500 doesn't seem to get sent to client. ctx.response.body = err // I don't think this `err` object makes it to client either. console.log('hi'); // This DOES run when there is an error }); ctx.response.type = 'application/pdf'; ctx.response.body = rs; }); Here is basically what I am trying to do:Create a PDF stream from the request body sent from the client.Pipe that stream to the HTTP responseHowever, in some cases the PDF might not be generated in which case createReadStream will throw an error.In the cases where there is an error, my fetch code in the client always gives a response of 404 even though I set the status to be 500 in my server code.tldr: Why isn't my server side code sending the right stuff to the client when there is an error? And am I not doing this error handling properly in general?

Submitted May 17, 2017 at 12:57PM by inhwjs

No comments:

Post a Comment