在此应用程序中,我使用async等待来尝试通过几个函数来处理API调用。在测试悲伤的路径错误路由时,我注意到该错误并未最终出现在中catch
。
开始整个过程的动作
export const submitBasicDetails = form => async dispatch => {
try {
const response = await interstitialHandlerPromise(Actions.SUBMIT_FORM, form); // <- we end up here
console.log('submitBasicDetails response', response); // <-- we see the error here
const {id} = response.data;
dispatch({
type: Actions.SUBMIT_FORM,
id
});
return response;
} catch (error) {
console.log('ACTION', error); // <-- instead of here :()
dispatch({
type: Actions.SUBMIT_FORM_FAIL,
id: null,
error: 'There was a server error, please try again later.'
});
}
};
然后,表单数据将命中该interstitialHandlerPromise
位置,我们在此决定要使用哪种API方法:
export const interstitialHandlerPromise = (type, data) => {
const {requestMethod, config} = determineRequestMethod(type);
const requests = requestMethod(data);
return new Promise((resolve, reject) =>
interstitialHandler(requests, config)
.then(response => resolve(response))
.catch(error => {
console.log('intersitial error', error);
reject(error);
})
);
};
最后postForm
是requests
上面函数内部的函数:
// /test will cause a 500 error since it doesn't exist
export const postForm = async (form, END_POINT = '/api/test') => {
const resPayload = form.data;
const resUrl = `${BASE_URL}${V1}${END_POINT}`;
try {
const res = await axios.post(resUrl, {...resPayload});
return {
res
};
} catch (e) {
console.log('postForm e', e); // <-- This hits because `/test` returns 500
return new Error(e.message);
}
};
得到它了!除了返回错误,我还需要抛出错误。
在postForm函数中:
} catch (e) {
console.log('postInitialLoss e', e);
throw new Error(e.message);
}
然后在intersitialHandlerPromise
:
export const interstitialHandlerPromise = async (type, data) => {
const {requestMethod, config} = determineRequestMethod(type);
const requests = requestMethod(data);
try {
const response = await interstitialHandler(requests, config);
return response;
} catch(e) {
throw new Error(e); // <- this gets hit
}
};
现在,我们终于回到动作中catch
:
} catch (error) {
console.log('ACTION (SHOULD GET HERE)!', error); // <-- WE are here! :D
dispatch({
type: Actions.SUBMIT_BASIC_DETAILS_FAIL,
initialLossCreated: false,
error: 'There was a server error, please try again later.'
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句