首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用AxiosRequestConfig的validateStatus函数处理Nestjs HttpService错误

用AxiosRequestConfig的validateStatus函数处理Nestjs HttpService错误
EN

Stack Overflow用户
提问于 2021-12-27 20:19:25
回答 1查看 4.2K关注 0票数 2

我需要处理http错误状态代码(如401、500等),这些代码在使用HttpService (HttpModule of Nestjs)消费外部服务时可能发生。以下是我正在进行的实施工作:

代码语言:javascript
运行
复制
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的执行。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-12-28 03:14:04

我实现了下一段代码,以便利用validateStatus函数的AxiosRequestConfig为我的需要提供解决方案:

代码语言:javascript
运行
复制
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<AxiosResponse<any>>而不是Observable<AxiosResponse<any>方法

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70500040

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档