index.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import {
  2. Injectable,
  3. NestInterceptor,
  4. ExecutionContext,
  5. CallHandler,
  6. HttpStatus,
  7. BadRequestException,
  8. } from '@nestjs/common';
  9. import { map, catchError } from 'rxjs/operators';
  10. import { Observable, throwError } from 'rxjs';
  11. export interface Response<T> {
  12. statusCode: number;
  13. data: T;
  14. }
  15. /**
  16. * transform response to client
  17. */
  18. @Injectable()
  19. export class TransformResInterceptor<T>
  20. implements NestInterceptor<T, Response<T>>
  21. {
  22. intercept(
  23. context: ExecutionContext,
  24. next: CallHandler,
  25. ): Observable<Response<T>> {
  26. return next
  27. .handle()
  28. .pipe(map((data) => ({ statusCode: HttpStatus.OK, data })));
  29. }
  30. }
  31. /**
  32. * Handle error in here.
  33. * Normally depend on status which from milvus service.
  34. */
  35. @Injectable()
  36. export class ErrorInterceptor implements NestInterceptor {
  37. intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
  38. return next.handle().pipe(
  39. catchError((err) => {
  40. console.error('---error interceptor---', err.response);
  41. if (err.response) {
  42. return throwError(err);
  43. }
  44. return throwError(new BadRequestException(err.toString()));
  45. }),
  46. );
  47. }
  48. }