[Question] Exception filter object with dependencies
I need to create global expection filter object (ApplicationExceptionFilter) that depends on the Logger component that is part of the ApplicationModule
Application module:
@Module({
components: [
Logger
]
})
export default class ApplicationModule { }
Logger:
@Component()
export class Logger {
log(message : string) {
// log somewhere
}
}
Expection filter:
@Catch(Error)
export class ApplicationExceptionFilter implements ExceptionFilter {
constructor(private logger : Logger) { }
catch(exception: Error, response: Response) {
this.logger.log('some message')
response.status(500).end()
}
}
Currently I create dependencies manually (I have 2 instances of an logger)
app.useGlobalFilters(new ApplicationExceptionFilter(new Logger()))
Is it possible to retrieve Logger instance from the ApplicationModule and pass it to the ApplicationExceptionFilter ?
Or is there a better solution for ExceptionFilter objects' dependencies management?
Hi @ddyrcz, The exception filters are detached from the modules scopes. The interceptors should fit the gap in your problem. http://www.docs.nestjs.com/interceptors :cat: Thanks, Kamil
@kamilmysliwiec, in exception-filters article => Global filters chapter is written:
Let's assume that we have a LoggerExceptionFilter registered in the LoggerModule. This LoggerModule is imported into the root module
You say:
The exception filters are detached from the modules scopes. The interceptors should fit the gap in your problem. http://www.docs.nestjs.com/interceptors 🐱
So, it means this docs should be updated?
Also in docs, will be good to add chapter navigation like in angular.io for ex. https://angular.io/guide/architecture#modules
Hi @ddyrcz, @kamilmysliwiec
There is another thing you can do.
import ApplicationExceptionFilter in ApplicationModule as provider, and export it.
It will make ApplicationExceptionFilter injectable with token.
the last thing is to use it in your main file:
...
app.useGlobalFilters(app.get(ApplicationExceptionFilter))
...
...
app.useGlobalFilters(app.get(ApplicationExceptionFilter))
...
It is working as long as ApplicationExceptionFilter does not depend on scope request provider. (trying to assign a request id on the log/error)
It is the same issue with an interceptors.
I think I have to use the HttpAdapterHost
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.