简体   繁体   中英

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.

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). 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. How can I send an error response with a json payload that can be caught in the catch handler?

you can send response in JSON format by changing

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

to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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