我正在我的应用程序中进行 API 调用。在某些情况下,API 将返回非 200 状态代码,并在响应正文中包含用户友好的消息。我在调用 API 时设置了一个 try catch 块。如果返回非状态,我将面临一些获取尸体的挑战。
响应正文是一个json字符串。
// example response 403 status code ....
{
"message": "Houston we have a problem"
}
try {
const results = [];
let result = [];
const response = await ky.get(`${this.state.api_base_url}/${path_parts.join("/")}?${query_parts.map(x => `${x.key}=${x.value}`).join("&")}`);
result = await response.json();
context.commit("set200response", result);
} catch (err) {
// I have tried each of the following without success
// this returns undefined
console.error("Non 200 Message", (err as any).response.data.message);
console.error("Non 200 Message", (err as any).response.data);
// this returns the promise object but I can not access its properties
console.error((err as any).response.json());
//this returns the generic message for a non 200 status
console.error("Generic Message", (err as any).message);
} finally {
context.commit("setLoading", false);
}
}
默认情况下,ky 从response.statusText 返回错误。 您需要更改拦截器中的错误消息。
这可以按如下方式完成:
import ky, { HTTPError } from 'ky';
const baseApi = ky.create({
prefixUrl: 'https://your_base_api_url',
});
const errorInterceptor = async (error: HTTPError) => {
const { response } = error;
const contentType = response.headers.get('content-type');
if (contentType?.indexOf('application/json') !== -1) {
error.message = await response.json();
} else {
error.message = await response.text();
}
return error;
};
const api = baseApi.extend({
hooks: {
beforeError: [errorInterceptor],
},
});
然后在你的组件文件中:
import api from 'file_above'
const queryParams = {
key1: 'param1'
key2: 'param2'
}
try {
const result = await api.get(path_parts, { searchParams: queryParams }).json();
context.commit('set200response', result);
} catch (err: any) {
//this returns the message for a non 200 status
console.error('Error Message:', err?.message);
} finally {
context.commit('setLoading', false);
}