0 api promise http-status-code-404 axios
我一直在尝试构建一个天气应用程序,但在验证 http 状态时遇到一些麻烦,以防用户自愿插入不存在的城市名称或用户在输入字段中输入错误。
唯一的问题是我找不到在 axios Promise 中插入 status !== 200 的方法。
200 状态工作得很好,但 404 状态却不行。我确信承诺中的某个地方有错误,但我无法找到解决方法。
此外,当我控制台记录错误时,它会显示以下消息:
console.log 中出现错误
Uncaught (in promise) Error: Request failed with status code 404
at e.exports (createError.js:16)
at e.exports (settle.js:17)
at XMLHttpRequest.E (xhr.js:66)
Run Code Online (Sandbox Code Playgroud)
JavaScript
try{
axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${api_key}`).then(
async response => {
let data = await response.data
if (response.status !== 200) {
throw new Error(response.status);
} else {
console.log(data)
document.getElementById('hum').textContent = data.main.humidity;
document.getElementById('feels-like').textContent = data.main.feels_like;
}}
)
} catch(error) {
if (response.status === 404) {
console.log(`Err: ${error}`);
throw err;
}
};
Run Code Online (Sandbox Code Playgroud)
任何建议都非常感激。谢谢你!
除非您调用 axios,否则您try/catch将不会捕获您在处理程序中抛出的拒绝.then(),也不会捕获本身抛出的任何拒绝。axiosawait
try {
await axios.get(...).then(...)
} catch(e) {
// now you can catch a rejection
}
Run Code Online (Sandbox Code Playgroud)
或者,当然,您.catch()也可以改为使用。
从风格上来说,这里不建议混合try/catch,await和。.then()你应该这样做:
try {
const response = await axios.get(...);
// process response here, including throw
} catch(e) {
// here you can catch a rejection, either from axios
// directly or from throwing in the processing
}
Run Code Online (Sandbox Code Playgroud)
或者:
axios.get(...).then(...).catch(...)
Run Code Online (Sandbox Code Playgroud)