DD DD
DD DD

Reputation: 1238

How to make custom response in pipe of nestjs

I made HttpExceptionFilter as below in nestjs.

import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
} from '@nestjs/common';
import { Response } from 'express';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception, host: ArgumentsHost) {
    const context = host.switchToHttp();
    const response = context.getResponse<Response>();
    const status = (exception.getStatus && exception.getStatus()) || 500;

    response.status(status).json({
      code: status,
      success: false,
    });
  }
}

And I put it into app.module to use it globally.

@Module({
  imports: [
  ],
  controllers: [AppController],
  providers: [
    AppService,
    {
      provide: APP_FILTER,
      useClass: HttpExceptionFilter,
    },
  ],
})

So far, it works very well except pipe of nestjs. I made a pipe and made it with @UsePipes in other controller.

This is my pipe code.

import { ArgumentMetadata, Injectable, PipeTransform } from '@nestjs/common';

@Injectable()
export class SplitEmailPipe implements PipeTransform<string, string> {
  transform(value: any, metadata: ArgumentMetadata): any {
    let email = '';
    try {
      email = value.split('@')[1];
    } catch (err) {
      throw new Error(err);
    }
    return { email };
  }
}

And I put that pipe using @UsePipes.
Pipe works well in this case.

  @Post('/')
  @UsePipes(new SplitEmailPipe())
  public async signIn(
    @Res() res,
    @Body() signInDto: SignInDto,
  ) {
    ... do something
  }

But the problem is HttpExceptionFilter doesn't work. It response by default response of nestjs.
Could you give me some advice for this problem?

Upvotes: 0

Views: 1312

Answers (1)

Ayoub Touba
Ayoub Touba

Reputation: 2997

That happens because you're not throwing an error from type HttpException, to fix this issue you should to replace :

  import { ArgumentMetadata, Injectable, PipeTransform } from '@nestjs/common';

@Injectable()
export class SplitEmailPipe implements PipeTransform<string, string> {
  transform(value: any, metadata: ArgumentMetadata): any {
    let email = '';
    try {
      email = value.split('@')[1];
    } catch (err) {
      throw new BadRequestException(err);
    }
    return { email };
  }
}

Upvotes: 1

Related Questions