NestJS中使用Axios的重试机制

ttygqcqt  于 2023-03-02  发布在  iOS
关注(0)|答案(1)|浏览(220)

我正在使用第三方API来获取一些数据,并在我的NestJS应用程序中执行一些操作,有时API会抛出一个400 Bad Request错误,因此在这种情况下,我只想在1秒后重试我的调用。
service.ts

async fetchData() {
  try {
    const response = await axios.get('my-api-irl')
    // .. doing some manipulation with the response
  } catch (error) {
    // I want to retry if the error status is equal to 400
  }
}
olmpazwi

olmpazwi1#

你可以 checkout library that I've published并执行该操作。如果你只想在400错误时重试,你可以这样实现:

import withRetry from "@teneff/with-retry/decorator";
import axios, { AxiosError } from "axios";

class ErrorOnWhichWeShouldRetry extends Error {
  constructor(readonly cause?: Error) {
    super();
  }
}

export class Something {
  @withRetry({
    errors: [ErrorOnWhichWeShouldRetry],
    maxCalls: 5,
    delay: 1000,
  })
  async fetchData() {
    try {
      const response = await axios.get("my-api-irl");
      return handleResponse(response);
    } catch (err) {
      if (isAxiosError(err) && err.code === '400') {
        throw new ErrorOnWhichWeShouldRetry(err);
      }
      throw err
    }
  }
}

const isAxiosError = (err: unknown): err is AxiosError => {
  return err instanceof Error && "code" in err;
};

相关问题