如何定义Axios错误响应的类型

发布于 2025-02-09 09:44:51 字数 1015 浏览 2 评论 0 原文

我打电话给API。我可以从Axios Response.Data 中收到两种响应类型。如果是200。 iindustrygrouplist 如果它的另一个错误(如400

export const GetIndustry = async () => {
    const base = Config.api_url;
    const endpoint = "/api/industry";
    const url = base + endpoint;

    try {
        const response = await HttpClient.get<IIndustryGroupList[]>(url, options);
        return [response, null] as const;
    } catch (err: any) {
        // here we can receive the axios response for a 400.
        return [null, err.response] as const;
    }
};

。代码> iapierRorresponse 。更具体地说 axios.Response.data 应为类型 iapierRorresponse

“在此处输入图像说明”

用法

const [response, error] = await GetIndustry();

// response.data of type IIndustryGroupList
// error.data of type IAPIErrorResponse

i am making a call to an api. There are 2 types of responses i can receive from axios response.data. If it's 200. IIndustryGroupList if its another error like 400. IAPIErrorResponse

export const GetIndustry = async () => {
    const base = Config.api_url;
    const endpoint = "/api/industry";
    const url = base + endpoint;

    try {
        const response = await HttpClient.get<IIndustryGroupList[]>(url, options);
        return [response, null] as const;
    } catch (err: any) {
        // here we can receive the axios response for a 400.
        return [null, err.response] as const;
    }
};

In the catch statement, when a 400 response is received i want to define the return response to be of type IAPIErrorResponse. more specifically axios.response.data should be of type IAPIErrorResponse

enter image description here

usage

const [response, error] = await GetIndustry();

// response.data of type IIndustryGroupList
// error.data of type IAPIErrorResponse

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

别再吹冷风 2025-02-16 09:44:51

我不确定您要实现的目标,但这肯定会给您达到想要的东西:

import axios, {
  AxiosRequestConfig,
  AxiosResponse,
} from 'axios';

type IIndustryGroupList = {
  somedata: string[]
}

type IAPIErrorDATA = {
  someerrorobject: object
}

type IAPIErrorResponse = {
  message: string,
  status: 400,
  data: IAPIErrorDATA
}

type ObjectWithProperty<P extends string> = {
  [K in P]: unknown
} & {
  [key: string]: unknown
}

const Config = {
  api_url: 'http://example.com',
};

/**
 *  Asserts that an object has a given property
 * @param value
 * @param property
 * @returns
 */
const objHasProperty = <P extends string>(
  value: unknown,
  property: P,
): value is ObjectWithProperty<P> => {
  if (typeof value !== 'object' || value === null) return false;
  if (property in value) return true;
  return false;
};

/**
 * Checks if an object is of `IAPIErrorResponse` type
 * @param response
 * @returns
 */
const isIAPIErrorResponse = (
  response: unknown,
): response is IAPIErrorResponse => {
  if (
    typeof response !== 'object'
    || response === null
  ) return false;

  if (
    objHasProperty(response, 'status')
    && objHasProperty(response, 'data')
    && response.status === 400
    // AND SOME OTHER CHECKS THAT ASSERT
    // YOUR OBJECT IS OF TYPE IAPIRESPONSE
  ) return true;

  return false;
};

/**
 * The HTTP client
 */
const HttpClient = {
  async get<T>(
    url: string,
    options: AxiosRequestConfig,
  ) {
    return axios.get<T>(url, options);
  },
};

/**
 * Your function
 * @returns
 */
export const GetIndustry = async (): Promise<
  [AxiosResponse<IIndustryGroupList[], any>, null]
| [null, IAPIErrorResponse]
> => {
  const base = Config.api_url;
  const endpoint = '/api/industry';
  const url = base + endpoint;
  const options = {};

  try {
    const response = await HttpClient.get<IIndustryGroupList[]>(
      url,
      options,
    );

    return [response, null];
  } catch (err: unknown) {
    if (
      objHasProperty(err, 'reponse')
      && isIAPIErrorResponse(err.response)
    ) return [null, err.response];

    const errMsg = `Unknown error${
      objHasProperty(err, 'message')
        ? `: ${err.message}.`
        : '.'
    }`;
    throw new Error(errMsg);
  }
};

(async () => {
  const [response, error] = await GetIndustry();
  if (error) {
    const r = response;
    // Here response is of type null
    const e = error;
    // And error is of type IAPIErrorResponse
    const { data } = error;
    // HERE! Data is of type IAPIErrorDATA
  } else {
    const { data } = response;
    // Here data is of type IIndustryGroupList[]
    const e = error;
    // And error is of type null
  }
})();

TSPlayground

I'm not reealy sure of what you are trying to achieve, but this will definitely give you the means to reach what you want:

import axios, {
  AxiosRequestConfig,
  AxiosResponse,
} from 'axios';

type IIndustryGroupList = {
  somedata: string[]
}

type IAPIErrorDATA = {
  someerrorobject: object
}

type IAPIErrorResponse = {
  message: string,
  status: 400,
  data: IAPIErrorDATA
}

type ObjectWithProperty<P extends string> = {
  [K in P]: unknown
} & {
  [key: string]: unknown
}

const Config = {
  api_url: 'http://example.com',
};

/**
 *  Asserts that an object has a given property
 * @param value
 * @param property
 * @returns
 */
const objHasProperty = <P extends string>(
  value: unknown,
  property: P,
): value is ObjectWithProperty<P> => {
  if (typeof value !== 'object' || value === null) return false;
  if (property in value) return true;
  return false;
};

/**
 * Checks if an object is of `IAPIErrorResponse` type
 * @param response
 * @returns
 */
const isIAPIErrorResponse = (
  response: unknown,
): response is IAPIErrorResponse => {
  if (
    typeof response !== 'object'
    || response === null
  ) return false;

  if (
    objHasProperty(response, 'status')
    && objHasProperty(response, 'data')
    && response.status === 400
    // AND SOME OTHER CHECKS THAT ASSERT
    // YOUR OBJECT IS OF TYPE IAPIRESPONSE
  ) return true;

  return false;
};

/**
 * The HTTP client
 */
const HttpClient = {
  async get<T>(
    url: string,
    options: AxiosRequestConfig,
  ) {
    return axios.get<T>(url, options);
  },
};

/**
 * Your function
 * @returns
 */
export const GetIndustry = async (): Promise<
  [AxiosResponse<IIndustryGroupList[], any>, null]
| [null, IAPIErrorResponse]
> => {
  const base = Config.api_url;
  const endpoint = '/api/industry';
  const url = base + endpoint;
  const options = {};

  try {
    const response = await HttpClient.get<IIndustryGroupList[]>(
      url,
      options,
    );

    return [response, null];
  } catch (err: unknown) {
    if (
      objHasProperty(err, 'reponse')
      && isIAPIErrorResponse(err.response)
    ) return [null, err.response];

    const errMsg = `Unknown error${
      objHasProperty(err, 'message')
        ? `: ${err.message}.`
        : '.'
    }`;
    throw new Error(errMsg);
  }
};

(async () => {
  const [response, error] = await GetIndustry();
  if (error) {
    const r = response;
    // Here response is of type null
    const e = error;
    // And error is of type IAPIErrorResponse
    const { data } = error;
    // HERE! Data is of type IAPIErrorDATA
  } else {
    const { data } = response;
    // Here data is of type IIndustryGroupList[]
    const e = error;
    // And error is of type null
  }
})();

TSPlayground

装纯掩盖桑 2025-02-16 09:44:51

您可以按照以下方式进行操作:

const response = await HttpClient.get<IIndustryGroupList[] | IAPIErrorResponse>(url, options);

You can do it in following way:

const response = await HttpClient.get<IIndustryGroupList[] | IAPIErrorResponse>(url, options);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文