Koa.js和流媒体。你如何处理错误?

时间:2017-10-28 11:13:16

标签: javascript error-handling streaming koa koa2

有人使用koa.js和溪流吗?

考虑这个例子

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

如果用户中止请求我得到

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

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

处理此类错误的正确方法是什么?

P.S。请求中止快递后我没有错误

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

P.P.S。我已经尝试了

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

但它没有效果。

1 个答案:

答案 0 :(得分:1)

使用gloabel错误处理程序。见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);