question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Cover error handling of Middleware in documentation

See original GitHub issue

I’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:open
  • Created 5 years ago
  • Reactions:9
  • Comments:9 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
futchdevcommented, Feb 6, 2021

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.

use(req: Request, res: Response, next: NextFunction) {
  try {
    if (error condition) {
        throw new HttpException('Not authorized', HttpStatus.UNAUTHORIZED);
    }
    next();
  } catch (e) {
    next(e); // if (e instanceof HttpException)
  }
}

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.

1reaction
jmcdo29commented, Sep 9, 2020

I’m wondering if I’m missing something here. If I do something like this

import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { APP_FILTER } from '@nestjs/core';
import { CatchAllFilter } from './catch-all.filter';

@Module({
  imports: [],
  controllers: [AppController],
  providers: [
    AppService,
    {
      provide: APP_FILTER,
      useClass: CatchAllFilter,
    },
  ],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply((req, res, next) => {
        throw new Error('Bad Request from Middleware');
      })
      .forRoutes('*');
  }
}

And I have a filter like

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

@Catch()
export class CatchAllFilter<T extends Error> implements ExceptionFilter {
  catch(exception: T, host: ArgumentsHost) {
    console.log(exception);
    const res = host.switchToHttp().getResponse();
    res.status(500).send({ message: exception.message });
  }
}

I’m able to catch the error thrown from the middleware, log it, and do any sort of transformation I need to on it.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Error handling - Express.js
Express comes with a built-in error handler that takes care of any errors that might be encountered in the app. This default error-handling...
Read more >
A Guide to Error Handling in Express.js | Scout APM Blog
Basic Quick Tutorial: Setting up Error Handling in Express.js · Step 1: Create and Setup Project · Step 2: Setup the Server ·...
Read more >
Handle errors in ASP.NET Core | Microsoft Learn
By Tom Dykstra. This article covers common approaches to handling errors in ASP.NET Core web apps. See Handle errors in ASP.
Read more >
Creating a custom ErrorHandlerMiddleware function
All .NET applications generate errors, and unfortunately throw exceptions, and it's important you handle those in your ASP.NET middleware ...
Read more >
How to create an error handler for your Express API
In Express, error handling middleware are middleware functions that accept four arguments: (error, request, response, next) . That first error ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found