Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

egg框架如何处理bodyParser的错误?

一旦请求体太大会报错:

2020-11-05 10:30:25,638 WARN 15522 [-/::1/-/5ms POST /file/upload?_csrf=65aNrQrDPCJFtxoR8PeLvdN9] nodejs.PayloadTooLargeError: request entity too large, check bodyParser config
    at readStream (/Users/laiyinan/Project/BackEnd/dolphinMusicV1/node_modules/raw-body/index.js:155:17)
    at executor (/Users/laiyinan/Project/BackEnd/dolphinMusicV1/node_modules/raw-body/index.js:112:5)
    at new Promise (<anonymous>)
    at getRawBody (/Users/laiyinan/Project/BackEnd/dolphinMusicV1/node_modules/raw-body/index.js:111:10)
    at AsyncFunction.module.exports [as json] (/Users/laiyinan/Project/BackEnd/dolphinMusicV1/node_modules/co-body/lib/json.js:39:21)
    at parseBody (/Users/laiyinan/Project/BackEnd/dolphinMusicV1/node_modules/koa-bodyparser/index.js:100:26)
    at bodyParser (/Users/laiyinan/Project/BackEnd/dolphinMusicV1/node_modules/koa-bodyparser/index.js:85:25)
    at dispatch (/Users/laiyinan/Project/BackEnd/dolphinMusicV1/node_modules/koa/node_modules/koa-compose/index.js:42:32)
    at dispatch (/Users/laiyinan/Project/BackEnd/dolphinMusicV1/node_modules/egg-static/node_modules/koa-compose/index.js:42:32)
    at /Users/laiyinan/Project/BackEnd/dolphinMusicV1/node_modules/koa-static-cache/index.js:39:69
message: "request entity too large, check bodyParser config"
expected: 116228823
length: 116228823
limit: 10485760
type: "entity.too.large"
pid: 15522
hostname: laiyinandeMacBook-Pro.local

我想把这个错误以及500状态返回给前端

我在config里这样写:

    onerror: {
      all(err, ctx) {
        console.log(err);
        ctx.body = 'error';
        ctx.status = 500;
      },
    },

能打印出来err但是没有返回500状态

我又改写一个中间件:

'use strict';

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

依然不行 如何才能捕获bodyParer的错误并返回给前端?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

读了一下源码
在koa-bodyParser里有预设了onerror

这样写:

bodyParser: {
      formLimit: '10mb',
      jsonLimit: '10mb',
      textLimit: '10mb',
      onerror:
        (err, ctx) => {
          console.log(err);
          ctx.body = 'error';
          ctx.status = 500;
        },
    },

可以返回错误了


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...