简体   繁体   English

使用 Next.js 和自定义服务器通过 JSON 负载捕获错误客户端

[英]Catching error client side with JSON payload using Next.js and custom server

I'm using Next.js with a custom server (Express) and coming across an issue with basic api error handling.我将 Next.js 与自定义服务器 (Express) 一起使用,但遇到了基本 api 错误处理的问题。

I have some simple error handling middleware which looks similar to this:我有一些简单的错误处理中间件,看起来类似于:

app.use((err, req, res) => {
    res.status(400).send(message);
});

If message is a string I'm able to catch the error client-side (when using fetch and promises).如果message是一个字符串,我可以在客户端捕获错误(使用 fetch 和 promises 时)。 However if I use something like:但是,如果我使用类似的东西:

res.status(400).send({ message });

This does not get caught but I can access the payload within the then handler of the promise.这不会被捕获,但我可以在承诺的then处理程序中访问有效负载。 How can I send an error response with a json payload that can be caught in the catch handler?如何使用可以在catch处理程序中捕获的 json 有效负载发送错误响应?

you can send response in JSON format by changing您可以通过更改以 JSON 格式发送响应

res.status(400).send({ message });

to

res.status(400).JSON({ error:message });

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

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