【发布时间】:2015-06-27 06:02:35
【问题描述】:
是否可以使用 Express 4 向前端发送 JSON 响应指示出现错误,以及在 Express 中间件内部调用 next(err),以便错误可以由服务器也是?还是这些调用完全相互排斥?
我目前的假设是你可以这样做:
app.get('/', function(req, res, next) {
res.json({ error : true });
});
你可以这样做:
app.get('/', function(req, res, next) {
next(new Error('here goes the error message');
});
但你不能这样做
app.get('/', function(req, res, next) {
res.json({ error : true });
next(new Error('here goes the error message');
});
你不能这样做:
app.get('/', function(req, res, next) {
next(new Error('here goes the error message');
res.json({ error : true });
});
【问题讨论】:
-
你能提供一些示例代码吗?
-
@kdbanman 喜欢什么?看起来像发送 json 然后调用
next. -
“以便服务器也可以处理错误”是什么意思?
-
@DaveNewton 这是一个关于函数调用兼容性的问题,所以包含显示他想要如何使用它们的代码不是更好吗?它消除了歧义。它使帮助变得更容易。这表明已经投入了一些努力。 (这是一个合法的问题 - 你有很多代表和元活动,而我没有。)
-
我添加了一些代码作为示例,但如果@robertklep 是正确的,那么这将回答问题