【问题标题】:How to handle "PayloadTooLargeError" with a response or a custom error?如何处理带有响应或自定义错误的“PayloadTooLargeError”?
【发布时间】:2021-12-10 12:33:19
【问题描述】:

我试图将有效负载限制为 1kb,使用:

app.use(bodyParser.json({
 limit: "1kb" ,
 strict:true
       }));

它工作正常,因为它应该工作,但唯一的问题是我得到一个 错误

PayloadTooLargeError: request entity too large
at readStream (E:\Work\FIGHTME\V1.0\api\node_modules\raw-body\index.js:155:17)
at getRawBody (E:\Work\FIGHTME\V1.0\api\node_modules\raw-body\index.js:108:12)
at read (E:\Work\FIGHTME\V1.0\api\node_modules\body-parser\lib\read.js:77:3)
at jsonParser (E:\Work\FIGHTME\V1.0\api\node_modules\body-parser\lib\types\json.js:135:5)
at Layer.handle [as handle_request] (E:\Work\FIGHTME\V1.0\api\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (E:\Work\FIGHTME\V1.0\api\node_modules\express\lib\router\index.js:317:13)
at E:\Work\FIGHTME\V1.0\api\node_modules\express\lib\router\index.js:284:7
at Function.process_params (E:\Work\FIGHTME\V1.0\api\node_modules\express\lib\router\index.js:335:12)
at next (E:\Work\FIGHTME\V1.0\api\node_modules\express\lib\router\index.js:275:10)
at expressInit (E:\Work\FIGHTME\V1.0\api\node_modules\express\lib\middleware\init.js:40:5)

有什么方法可以通过回调或其他方式处理此错误,以便我显示自定义错误或发送自定义响应?

【问题讨论】:

    标签: javascript node.js express body-parser


    【解决方案1】:

    你有没有这样尝试过

    app.use(express.json({limit: '1kb'}));
    

    在 Express v4.16.0 及更高版本中可以将请求正文解析为中间件。

    编辑

    如果您想自定义错误消息,则需要定义错误处理程序中间件来执行此操作。像这样的:

    // Not tested code.
    // Usually added as last middleware
    app.use(function (err, req, res, next) {
        if(err instanceof PayloadTooLargeError){
            //res.status(<your status code>).send(<your response>);
            res.status(400).send("Customized Response");
        }
        else{
            next(err);
        }
    })
    

    【讨论】:

    • 您好先生,谢谢您的回复,我的限制器工作正常,我只是想知道我是否能够自定义我的错误消息并发送自定义响应
    猜你喜欢
    • 2021-05-26
    • 2023-03-12
    • 2019-05-31
    • 1970-01-01
    • 2021-05-30
    • 2019-10-19
    • 2010-11-12
    • 2014-10-02
    • 2017-10-09
    相关资源
    最近更新 更多