【发布时间】:2019-11-08 09:28:36
【问题描述】:
我想知道处理响应中的错误的最佳方法 - 请求。 我有收到请求的这条路线:
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 块。
我应该像这样发送错误:
res.send({error: "The data wasn't load"})
我应该设置这样的状态吗?
res.status(500).send({error: "The data wasn't load"})
或者我应该使用不同的状态代码设置状态吗?
基于此,在我的前端方法 getInfo() 中处理它以获取错误并在 Web 界面上显示错误消息的最佳方法是什么?
我应该像这样在.then 块内做一个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 块中处理这个错误
getInfo () {
axios.get(process.env.REACT_APP_HOST + '/getInfo')
.then(resp => {
this.appInfoHandler(resp.data)
})
.catch(function (error) {
//print error message on web interface
})
}
【问题讨论】:
标签: javascript node.js reactjs express try-catch