简体   繁体   English

NodeJs表达错误中间件解析

[英]NodeJs express error middleware parsing

I am trying to write a middleware to handle errors. 我正在尝试编写一个中间件来处理错误。 But I cannot figure out how to send the correct format to my frontend. 但是我不知道如何将正确的格式发送到前端。 Below I am going to list all of my attempts in hopes of helping you help me. 在下面,我将列出我的所有尝试,希望对您有所帮助。

Attempt 1 尝试1

app.use(function(err, req, res, next) {
    const formatted = err;
    res.send(formatted)
});

result in postman 导致邮递员

{ "code": 422 } {“代码”:422}

Attempt 2 尝试2

app.use(function(err, req, res, next) {
    const formatted = `${err}`;
    res.send(formatted)
});

result (postman) 结果(邮递员)

Error: Request returned error code: 422 and body: {"status":422,"title":"The display name: build_id has already been used on this product.","type":" https://developer.bigcommerce.com/api#api-status-codes ","errors":{"display_name":"The display name: build_id has already been used on this product."}} 错误:请求返回的错误代码:422和正文:{“ status”:422,“ title”:“显示名称:build_id已在此产品上使用。”,“ type”:“ https://developer.bigcommerce .com / api#api-status-codes “,”错误“:{” display_name“:”显示名称:build_id已在该产品上使用。“}}

That is the data i want but i need it in json 那是我想要的数据,但我需要在json中

Question Why is there more data revealed after string interpolation? 问题为何在插入字符串后还会显示更多数据? How can i format it to json? 我如何将其格式化为json?

You're probably looking for res.json(err) if I had to guess? 如果我不得不猜测,您可能正在寻找res.json(err)

https://expressjs.com/en/api.html#res.json https://expressjs.com/zh-CN/api.html#res.json

EDIT: Full example: 编辑:完整示例:

app.use(function(err, req, res, next) {
    if (err) res.json(err)
});

You can do it in this way 你可以这样

app.use(function(err, req, res, next) {
    if (err) {
        res.json({
            status: "error",
            error: `${err}` // <-- edited
        });
    } else {
        next();
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM