#@UseFilters usage in service classes

7 messages · Page 1 of 1 (latest)

past dock
#

Hi Community! I was initially following the https://github.com/nestjs/nest/tree/master/sample/18-context/src example to build a standalone cron in NestJS + trying to enhance it with a custom filter

example service I've built

import { Injectable } from '@nestjs/common';
import {MyWorkerExceptionFilter} from './'

@Injectable()
@UseFilters(MyWorkerExceptionFilter)
export class AppService {
  getHello(): string {
    throw new Error('')
    // return 'Hello world!';
  }
}

However, the filter doesn't seems to be able to catch errors at at all!

Was @UseFilters designed to be used on controllers/module config only, without support on ad hoc service classes?

(note: was attempting to check the availability very fast, can provide an repro example once asked

GitHub

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀 - nestjs/nest

nocturne snow
#

Filters and other enhancers only work on controllers. That's the boundary where Nest hands you the control of the execution flow. That means - Nest handles the requests, runs enhancers and calls the controller method. Then, you're in charge of calling the service methods and do your own error handling (Nest doesn't have a way to put any logic between these direct service calls). Errors not handled there will be caught by the filter bound to the controller method.

past dock
# nocturne snow Filters and other enhancers only work on controllers. That's the boundary where ...

Right right, in other words, if I were to use the template of Standalone Applications

For exception handling, I'll most likely having to design my own decorator/layer to bake in these logic, other than reusing the @UseFilters design yeh?

nocturne snow
#

What kind of application are you building may I ask?

past dock
#

It's a cron/k8s job 😃, with the desire the log details if there were custom errors thrown

nocturne snow
#

Right. Cron "controllers" don't support filters. Precisely because there's nowhere to return the error response to.