Search code examples
requesttry-catchnestjsnestendpoint

NestJS: Hit default endpoint when 404 (endpoint not found)


I'd like to create some sort of catch all endpoint that will account for different request types: Get, Post, Options, etc. and also any request. Something like the following:

@CatchAll('*')
public notFound {
  return 'Endpoint not found';
}

Does anything like this exist in NestJS?


Solution

  • By default if you request an endpoint that doesn't exist NestJS will return a 404 response with a payload similar to the following:

    {
        "statusCode": 404,
        "message": "Cannot GET /your-endpoint",
        "error": "Not Found"
    }
    

    I don't know about the specific use case, but if you want, it is possible to create a custom exception filter that will catch everything (or a specific error you want to throw). You can create a custom filter by implementing ExceptionFilter and check the error type to return a custom payload

    @Catch()
    export class AllExceptionsFilter implements ExceptionFilter {
      constructor(private readonly httpAdapterHost: HttpAdapterHost) {}
    
      catch(exception: unknown, host: ArgumentsHost): void {
    
        const ctx = host.switchToHttp();
    
        // check the httpStatus code and add custom logic if you want
        const httpStatus =
          exception instanceof HttpException
            ? exception.getStatus()
            : HttpStatus.INTERNAL_SERVER_ERROR;
    
        const responseBody = {
           // ... your custom response body
        };
    
        this.httpAdapterHost.httpAdapter.reply(ctx.getResponse(), responseBody, httpStatus);
      }
    }
    

    And enable the exception filter as global in your main.ts file

    const http_adapter = app.get(HttpAdapterHost);
    app.useGlobalFilters(new AllExceptionsFilter(http_adapter));