我想知道处理响应中错误的最佳方法 - 请求。 我有这条路线接收请求:
app.get('/getInfo', function (req, res, next) {
let obj = {}
try {
obj = {
...
date: lastUpdatedDate('./utils/appVersion.js'),
...
}
res.status(200).send(obj)
} catch (error) {
console.log(error.message)
res.send({error: "The data wasn't load"})
}
})
以及发出请求的这个函数
getInfo () {
axios.get(process.env.REACT_APP_HOST + '/getInfo')
.then(resp => {
this.appInfoHandler(resp.data)
})
.catch(function (error) {
console.log(error)
})
}
如果错误发生在服务器端,最好的处理方法是什么?
假设在此代码块中目录不存在:lastUpdatedDate('./directoreyDoesntExists/appVersion.js'),
所以我的代码转到 catch
block 。
我应该像这样发送错误吗:
res.send({error: "The data wasn't load"})
我应该设置这样的状态吗?
res.status(500).send({error: "The data wasn't load"})
或者我应该使用不同的状态代码设置状态吗?
基于此,在我的前端方法 getInfo()
中获取错误并在 Web 界面上显示错误消息的最佳处理方法是什么?
我应该像这样在 .then
block 中执行 if else
吗?
getInfo () {
axios.get(process.env.REACT_APP_HOST + '/getInfo')
.then(resp => {
if(resp.status === 200){
this.appInfoHandler(resp.data)
}else if (resp.status === 400){
//print error message on web interface
}else if (resp.status === 500){
//print error message on web interface
})
.catch(function (error) {
console.log(error)
})
或者我应该像这样直接在 catch
block 中处理这个错误
getInfo () {
axios.get(process.env.REACT_APP_HOST + '/getInfo')
.then(resp => {
this.appInfoHandler(resp.data)
})
.catch(function (error) {
//print error message on web interface
})
}
最佳答案
对于这种情况
res.send({error: "The data wasn't load"})
对比
res.status(500).send({error: "The data wasn't load"})
发送一个状态只是更详细,但两者都可以。 检查Proper way to set response status and JSON content
对于这种情况,取决于你需要什么
then(resp => {
if(resp.status === 200){
this.appInfoHandler(resp.data)
}else if (resp.status === 400){
//print error message on web interface
}else if (resp.status === 500){
//print error message on web interface
})
.catch(function (error) {
console.log(error)
})
对比
getInfo () {
axios.get(process.env.REACT_APP_HOST + '/getInfo')
.then(resp => {
this.appInfoHandler(resp.data)
})
.catch(function (error) {
//print error message on web interface
})
}
您可以处理所有将它们发送到 catch block 的错误
else if (resp.status === 400){
//print error message on web interface
不在此处打印错误,而是抛出一个新错误并将其发送到 catch block
throw new ApiError("UserNotFount",400,"not found");
throw new Error('Error 400, not found');
关于javascript - 使用 nodejs + express 处理服务器端和客户端错误的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56772727/