mig*_*gnz 11 javascript promise axios
我试图用Axios更好地理解JavaScript Promise。我假装是处理Request.js中的所有错误,并且仅从任何地方调用请求函数而不必使用catch()。
在此示例中,对请求的响应将为400,并带有JSON错误消息。
这是我得到的错误:
Uncaught (in promise) Error: Request failed with status code 400
我找到的唯一解决方案是.catch(() => {})在Somewhere.js中添加,但我试图避免这样做。可能吗?
这是代码:
Request.js
export function request(method, uri, body, headers) {
let config = {
method: method.toLowerCase(),
url: uri,
baseURL: API_URL,
headers: { 'Authorization': 'Bearer ' + getToken() },
validateStatus: function (status) {
return status >= 200 && status < 400
}
}
...
return axios(config).then(
function (response) {
return response.data
}
).catch(
function (error) {
console.log('Show error notification!')
return Promise.reject(error)
}
)
}
Run Code Online (Sandbox Code Playgroud)
Somewhere.js
export default class Somewhere extends React.Component {
...
callSomeRequest() {
request('DELETE', '/some/request').then(
() => {
console.log('Request successful!')
}
)
}
...
}
Run Code Online (Sandbox Code Playgroud)
elo*_*ire 60
如果您想访问整个错误正文,请按如下所示操作:
async function login(reqBody) {
try {
let res = await Axios({
method: 'post',
url: 'https://myApi.com/path/to/endpoint',
data: reqBody
});
let data = res.data;
return data;
} catch (error) {
console.log(error.response); // this is the main part. Use the response property from the error object
return error.response;
}
}
Run Code Online (Sandbox Code Playgroud)
Md.*_*afi 59
你可以这样:
error.response.data
在我的例子中,我从后端得到了error属性。所以,我使用了error.response.data.error
我的代码:
axios
.get(`${API_BASE_URL}/students`)
.then(response => {
return response.data
})
.then(data => {
console.log(data)
})
.catch(error => {
console.log(error.response.data.error)
})
Run Code Online (Sandbox Code Playgroud)
use*_*718 21
如果你想使用异步等待尝试
export const post = async ( link,data ) => {
const option = {
method: 'post',
url: `${URL}${link}`,
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
data
};
try {
const response = await axios(option);
} catch (error) {
const { response } = error;
const { request, ...errorObject } = response; // take everything but 'request'
console.log(errorObject);
}
Run Code Online (Sandbox Code Playgroud)
Pla*_*tta 20
实际上,到目前为止,axios无法实现。2xx只能包含在范围内的状态代码.then()。
常规方法是在catch()块中捕获错误,如下所示:
axios.get('/api/xyz/abcd')
.catch(function (error) {
if (error.response) {
// Request made and server responded
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
});
Run Code Online (Sandbox Code Playgroud)
另一种方法可以是拦截请求或响应,然后再由then或catch处理。
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
Run Code Online (Sandbox Code Playgroud)
为了可重用性:
创建文件 errorHandler.js:
export const errorHandler = (error) => {
const { request, response } = error;
if (response) {
const { message } = response.data;
const status = response.status;
return {
message,
status,
};
} else if (request) {
//request sent but no response received
return {
message: "server time out",
status: 503,
};
} else {
// Something happened in setting up the request that triggered an Error
return { message: "opps! something went wrong while setting up request" };
}
};
Run Code Online (Sandbox Code Playgroud)
然后,每当你发现 axios 错误时:
Just import error handler from errorHandler.js and use like this.
try {
//your API calls
} catch (error) {
const { message: errorMessage } = errorHandlerForAction(error);
//grab message
}
Run Code Online (Sandbox Code Playgroud)
小智 5
我尝试使用该try{}catch{}方法,但它对我不起作用。但是,当我切换到 using 时.then(...).catch(...),AxiosError 被正确捕获,我可以使用它。当我在放置断点时尝试前者时,它不允许我看到 AxiosError,而是告诉我捕获的错误是未定义的,这也是最终在 UI 中显示的内容。
不知道为什么会发生这种情况,我觉得这很微不足道。无论哪种方式,我建议使用.then(...).catch(...)上面提到的传统方法来避免向用户抛出未定义的错误。
| 归档时间: |
|
| 查看次数: |
20601 次 |
| 最近记录: |