在这里与新手联系。我在使用react fetch api并尝试引发自定义错误时遇到问题。我有一个在localhost:8080上运行的rest api端点。从那以后,我已经关闭了该流程(模仿停机服务),我想抛出一个更具描述性的错误,而不是标准的“无法获取”错误。似乎代码拒绝了我的上述错误,并使用默认的提取错误。有没有办法覆盖这个?
fetchData() {
fetch('http://localhost:8080/locales/all')
.then(function(response) {
if (response.ok) {
return response.json();
}
throw Error('Oops, looks like the service is down :-(');
})
.then(parsedJSON => {
this.setState({
locales: parsedJSON.content,
isLoading:false
});
}).catch(error => {
this.setState({
error: error.message,
isLoading:false
});
console.log(error.message); // results in Failed to fetch
});
答案 0 :(得分:1)
问题在于,最初的thread_time
调用可以使用fetch
对象来解决,但是如果Response
完全失败,它将根本无法解决,并将直接进入fetch
。如果将其放在代码中,这将很清楚:
catch
当您看不到fetch('http://localhost:8080/locales/all')
.then(function(response) {
console.log('got a response');
时,将无法got a response
内的throw
自定义错误消息。
.then
相反,您可以在function fetchData() {
fetch('http://localhost:8080/locales/all')
.then(function(response) {
console.log('got a response');
if (response.ok) {
return response.json();
}
throw new Error('Oops, looks like the service is down :-(');
}).catch(error => {
console.log(error.message);
});
}
fetchData();
本身内部更改错误消息:
catch
}).catch(error => {
if (error.message === 'Failed to fetch') {
// change the message, or handle as needed:
error.message = 'Oops, looks like the service is down :-(';
}