【问题标题】:Axios does not catch error even not enter in catch block即使没有进入catch块,axios也不会捕获错误
【发布时间】:2021-09-23 06:03:50
【问题描述】:

我正在尝试获取 Axios 捕获块中的错误状态代码 413。我尝试了不同的解决方案,但对我没有任何效果。您能否检查一下出了什么问题。

uploadNewDatDocuments(datId, files = [], additionalInfo = {}) {
    return new Promise((resolve, reject) => {
        let url = new URL(this.baseUrl + this.uploadDocument.replace('{id}', datId));
        Object.keys(additionalInfo).forEach(queryParam => url.searchParams.set(queryParam, additionalInfo[queryParam]));
        let formData = new FormData();
        files.forEach(file => formData.append('files', file));
        axios
            .post(url.toString(), formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            })
            .then(response => {
                resolve(response.data);
            })
            .catch(error => {
                console.log("error occurred")
                reject(error);
            }).finally(error=>{
                console.log(error);
            })
    });
}

这是我的操作代码。

export function uploadNewDocuments(datId, additionalInfo = {}, attachments = [], comment = {}) {
return dispatch => {
    datService
        .uploadNewDatDocuments(datId, attachments, additionalInfo)
        .then(response => {
            const attachmentsIds = response.map(attachment => attachment.id);
            dispatch(
                DatCommentActions.addDatNewComment(datId, {
                    ...comment,
                    message: { ...comment.message, attachments: attachmentsIds }
                })
            );
        })
        .catch(error => {
            dispatch(MessageActions.showMessage({ message: error.response.data.message }));
            console.error(error);
        });
};

}

【问题讨论】:

    标签: reactjs axios


    【解决方案1】:

    413 Request Entity Too Large 实际上并不是错误,它是一个不成功的响应,除非响应中有实际错误,否则 catch 不会触发。

    你可以做的是检查 response.status 并在此基础上编写自己的 error 处理。

    【讨论】:

    • I can't event get 413 status code In .then.
    • 在浏览器的网络中,您会得到 413? @MehmoodZaman
    • 是的,我在网络选项卡中得到 413。
    • 如果你 console.log 响应然后在 uploadNewDatDocuments 中然后在你的调度函数 uploadNewDocuments 然后响应,你能告诉我结果吗?
    猜你喜欢
    • 2018-04-19
    • 2019-03-03
    • 2022-11-30
    • 1970-01-01
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    相关资源
    最近更新 更多