如何在不使节点服务器崩溃的情况下将错误返回给客户端客户端? [英] How to return error to the client client without making node server crash?
问题描述
我在节点服务器中有一条路由.当请求失败时,我需要发回一个错误,以便在前端轻松捕获.
I have a route in a node server. When the request fails, I need to send back an error that I can easily catch in my front-end.
基本上,我是这样的:
// server
app.get("/user/:id", async (req, res) => {
try{
const user = User.find(req.params.id)
return res.status(200).json({user});
}
catch(err){
throw new Error("error.user.route")
}
});
// front
function fetchUser(id){
return api.get("/user/" + id)
.then(res=> res.data.user)
.catch(err=> err.message)
}
// somewhere in the dom
error && error.message
它工作正常,我可以将明确的错误消息传递给客户端,但是当服务器抛出错误时,它也会停止.在本地开发中,完全可以调试,但是我无法在生产中使用这种行为.
It works fine, I can pass clear error messages to the client, but when the server throws an error, it also stops. In local development it's perfectly fine to debug, but I can't have this behavior in production.
我试图简单地发送 new Error(我的消息")
而不是抛出,但是它并没有出现在 catch
中.我可以发送 res.json({error:我的消息"})
,但是我想避免在前端处理带有条件的错误.
I've tried to simply send a new Error("my message")
instead of throwing, but it doesn't land in the catch
. I could send res.json({error: "my message"})
, but I'd like to avoid handling errors with conditions in my frontend.
是否有一种方法可以确保节点中的错误始终在不使服务器崩溃的情况下落在api调用的陷阱中?
Is there a way to make sure an error in node always lands in the catch of an api call without making the server crash?
推荐答案
最好将状态代码发送到前端 https://restfulapi.net/http-status-codes/
it`s better to send status code to frontend https://restfulapi.net/http-status-codes/
app.get("/user/:id", async (req, res) => {
try{
const user = User.find(req.params.id)
if(!user) {
res.status(404).json({error: "User not found"});
}
return res.status(200).json({user});
}
catch(err){
return res.status(500).json({error: "my message"});
}
});
并在express https中添加默认错误处理://expressjs.com/en/guide/error-handling.html#the-default-error-handler
And add default error handling in express https://expressjs.com/en/guide/error-handling.html#the-default-error-handler
这篇关于如何在不使节点服务器崩溃的情况下将错误返回给客户端客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!