我正在编写REST API并尝试正确处理任何错误。
当API调用成功时,成功对象将返回到调用函数,并将响应发送到客户端。但是如果发生错误,我想将错误返回给调用函数,以便我可以向客户端发送错误消息。
router.delete('/project', (req, res) => {
return DeleteProject(userId, projectId)
.then((response) => {
//handle response
});
});
DeleteProject: (userId, projectId) => {
return deleteProject(userId, projectId)
.then((response) => {
return response
})
.catch((error) => {
console.log('Error in DeleteProject:', error) // This happens.
return error; // this doesn't happen.
})
},
function deleteProject(userId, projectId) {
return Project.deleteOne( ... delete the project... )
.then((response) => {
return response
})
.catch((error) => {
return error
})
}
上面的中间函数中的.catch(错误),DeleteProject(),在发生错误时触发(即,控制台日志发生),但是返回并没有让它回来到路由器。
如何返回路由器要处理的错误?
答案 0 :(得分:2)
您可以从其他两个函数中删除catch
方法,并将catch
函数放入路由器本身。然后错误将自身传播到您的路由器功能
router.delete('/project', (req, res) => {
return DeleteProject(userId, projectId)
.then((response) => {
//handle response
}).catch(() => {
// Add catch function here. Any error in "DeleteProject" and "deleteProject" will propagate to here
})
});
DeleteProject: (userId, projectId) => {
return deleteProject(userId, projectId)
.then((response) => {
return response
});
// Remove catch function
},
function deleteProject(userId, projectId) {
return Project.deleteOne( ... delete the project... )
.then((response) => {
return response
});
// Remove catch function
}
答案 1 :(得分:1)
要通过promise chain传播错误,您需要抛出它们。在catch
处理程序中,当您返回错误而不是抛出错误时,您可以将promise的(成功)解析值设置为错误。