Koa.js and streaming. How do you handle errors?

Does anyone work with koa.js and threads?

Consider this example

const fs = require('fs');
const Koa = require('koa');

const app = new Koa();

app.use(async (ctx) => {
  ctx.body = fs.createReadStream('really-large-file');
});

app.listen(4000);

If the user aborts the request, I get either

  Error: read ECONNRESET
      at _errnoException (util.js:1024:11)
      at TCP.onread (net.js:618:25)

or

  Error: write EPIPE
      at _errnoException (util.js:1024:11)
      at WriteWrap.afterWrite [as oncomplete] (net.js:870:14)

What is the right way to deal with these types of errors?

PS I have no errors after the request is interrupted with the expression

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

const app = express();

app.get('/', (req, res) => {
  fs.createReadStream('really-large-file').pipe(res);
});

app.listen(4000);

PPS I tried

app.use(async (ctx) => {
  fs.createReadStream('really-large-file').pipe(ctx.res);
  ctx.respond = false;
});

But it had no effect.

+4
source share
1 answer

Use the gloabel error handler. see https://github.com/koajs/koa/wiki/Error-Handling

const fs = require('fs');
const Koa = require('koa');

const app = new Koa();


app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.status = err.status || 500;
    ctx.body = err.message;
    ctx.app.emit('error', err, ctx);
  }
});

app.use(async (ctx) => {
  ctx.body = await openFile();
});

function openFile(){
  return new Promise((resolve,reject)=>{
    var stream = fs.createReadStream("really-large-file")
    var data
    stream.on("error",err=>reject(err))
    stream.on("data",chunk=>data+=chunk)
    stream.on("end",()=>resolve(data))
  })
}

app.listen(4000);
+1
source

Source: https://habr.com/ru/post/1688333/


All Articles