Cover error handling of Middleware in documentation
See original GitHub issueI’d like to file a:
[ X ] Documentation issue or request
Nowhere in Nest v5 docs is an example to be found how to handle errors originating from middleware. Neither in the Exception Filter
section nor in the Middleware
section.
I also tried to put my Filter on the Middleware itself - doesn’t get executed either:
import { CsurfMiddleware as NestCsurfMiddleware } from '@nest-middlewares/csurf';
import { UseFilters, Injectable } from '@nestjs/common';
import { CSRFExceptionFilter } from './csrf-exception.filter';
@UseFilters(
new CSRFExceptionFilter(),
)
@Injectable()
export class CsurfMiddleware extends NestCsurfMiddleware {}
This guy seems to have the same question but it’s left unanswered: https://github.com/nestjs/nest/issues/294
I would argue this is a rather common use case as Middleware is based on express middleware in many cases throwing all kinds of typescript unfriendly errors you might want to catch / transform.
So a concrete documentation requests would be:
- How / where to handle errors coming from middleware
I’d be happy to contribute it myself, but I couldn’t figure out how to do it until now. So if someone points me to the right direction i will write it up for the docs.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:9
- Comments:9 (1 by maintainers)
Top GitHub Comments
The lack of info regarding Error handling + Middleware drove me crazy for days as well…but it seems the answer is pretty simple. The above examples apply to function middleware. For Class-based middleware, exceptions can be handled gracefully (ie. not shut the app down) by passing them directly into the next() callback. You can either wrap your block with try/catch and use a single next(err); to catch the error or, return next(err); everywhere. NestMiddleware will handle the error and send a response to the client.
If you wish to log the error or customise/override the response message on it’s way out, refer to jmcdo29 's sample code above to @\Catch and provide the APP_FILTER.
I’m wondering if I’m missing something here. If I do something like this
And I have a filter like
I’m able to catch the error thrown from the middleware, log it, and do any sort of transformation I need to on it.