5 javascript promise axios vuejs2
嗨,如果我的问题没有正确表述,我是新手,很抱歉。
我想在全局函数中定义来自 axios js 的承诺。在这里,我想全局处理/捕获 401 状态并注销用户。我不想在每个查询中都处理它。
这是我处理请求的源全局函数:
export function requestData (url, payload = {}) {
return axios.post(url, payload)
.then(response => {
return response.data
})
.catch(error => {
if (error.response.status === 401) {
logout()
} else {
return error
}
})
}
Run Code Online (Sandbox Code Playgroud)
这是我在控制器上使用的示例函数:
requestData('/api/persons', {options: this.options, search: search})
.then(data => {
this.data = data
})
.catch(error => {
this.error = error.toString()
})
Run Code Online (Sandbox Code Playgroud)
我的问题是,当出现异常时,我的控制器中的承诺捕获不会触发。如何实现这一点?
替换return error为throw error是事半功倍。
当我是对的时候,throw errorin Promise catch 不会调用下一个 Promise .catch 语句。这将在 .then 语句中起作用。
这样它应该可以工作:
export function requestData (url, payload = {}) {
return axios.post(url, payload)
.then(response => {
return response.data
})
.catch(error => {
if (error.response.status === 401) {
logout()
} else {
return error
}
})
.then(result => {
if (result instanceof Error) {
throw result
} else {
return result
}
})
}
Run Code Online (Sandbox Code Playgroud)