[英]Nestjs HttpService error handling with AxiosRequestConfig's validateStatus function
我需要處理使用 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;
}
}
在上面的代碼中,我只需要 function catchError
拋出自定義錯誤,但我無法使 function validateStatus
觸發catchError
的執行。
我已經實現了下一個代碼,以便利用 AxiosRequestConfig 的validateStatus
AxiosRequestConfig
來滿足我的需求:
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>
方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.