How to use validation in NestJs with HTML rendering?

0

Issue

NestJS uses validation with validation pipes and

@UsePipes(ValidationPipe)

If this fails it throws an exception. This is fine for REST APIs that return JSON.

How would one validate parameters when using HTML rendering and return

{ errors: ['First error'] }

to an hbs template?

Solution

You can create an Interceptor that transforms the validation error into an error response:

@Injectable()
export class ErrorsInterceptor implements NestInterceptor {
  intercept(
    context: ExecutionContext,
    call$: Observable<any>,
  ): Observable<any> {
    return call$.pipe(
        // Here you can map (or rethrow) errors
        catchError(err => ({errors: [err.message]}),
      ),
    );
  }
}

You can use it by adding @UseInterceptors(ErrorsInterceptor) to your controller or its methods.

Answered By – Kim Kern

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More