我想知道处理响应中错误的最佳方法 - 请求。我有一条收到请求的路线:
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 界面上显示错误消息的最佳方法是什么?
我应该像这样if else
在.then
块内做一个吗?
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
})
}