【问题标题】:Nestjs HttpService error handling with AxiosRequestConfig's validateStatus functionNestjs HttpService 错误处理与 AxiosRequestConfig 的 validateStatus 函数
【发布时间】:2022-01-26 16:30:12
【问题描述】:

我需要处理使用 HttpService(Nestjs 的 HttpModule)使用外部服务时可能发生的 http 错误状态代码(例如 401、500 等)。这是我正在处理的实现:

import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { Logger } from '@nestjs/common';
import { AxiosRequestConfig } from 'axios';
import { catchError, firstValueFrom, map } from 'rxjs';

type Person = {
  name: string;
  lastName: string;
};

@Injectable()
export class PersonService {
  constructor(private httpService: HttpService) {}
  async findPerson(): Promise<Person> {
    const axiosConfig: AxiosRequestConfig = {
      method: 'get',
      url: 'https://service.dns/path/person',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${jwt}`,
      },
      validateStatus: function (status: number) {
        return status === 200;
      },
    };

    const personInstance: Person = await firstValueFrom(
      this.httpService.request(axiosConfig).pipe(
        catchError((e) => {
          Logger.error(e.response.data.errorMessage);
          throw new Error('internal communication error');
        }),
        map((res) => {
          return res.data;
        }),
      ),
    );
    return personInstance;
  }
}

在上面的代码中,我只需要函数catchError抛出自定义错误,但我无法使函数validateStatus触发catchError的执行。

【问题讨论】:

标签: node.js typescript nestjs httpmodule httpservice


【解决方案1】:

我已经实现了下一个代码,以便利用AxiosRequestConfigvalidateStatus 函数来解决我的需求:

import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { Logger } from '@nestjs/common';
import { AxiosRequestConfig } from 'axios';
import { firstValueFrom } from 'rxjs';

type Person = {
  name: string;
  lastName: string;
};

@Injectable()
export class PersonService {
  constructor(private httpService: HttpService) {}
  async findPerson(): Promise<Person> {
    const axiosConfig: AxiosRequestConfig = {
      method: 'get',
      url: 'https://service.dns/path/person',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer fake_jwt`,
      },
      validateStatus: function (status: number) {
        return status === 200;
      },
    };

    return firstValueFrom(this.httpService.request(axiosConfig))
      .then((res) => res.data)
      .catch((e) => {
        Logger.error(e.errorMessage);
        throw new Error('internal communication error');
      });
  }
}

注意:此代码处理 Promise&lt;AxiosResponse&lt;any&gt;&gt; 而不是 Observable&lt;AxiosResponse&lt;any&gt; 方法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-27
    • 2021-12-27
    • 2019-08-31
    • 2022-09-23
    • 2020-03-18
    • 2020-10-24
    • 2021-12-21
    • 2019-01-25
    相关资源
    最近更新 更多