GuardAPI Logo
GuardAPI

Fix Improper Error Handling in NestJS

Improper error handling is a reconnaissance gift for attackers. By default, unhandled exceptions in NestJS can leak stack traces, database schema details, and internal logic. To secure the application, you must implement a centralized Exception Filter to sanitize outgoing error messages and log the actual technical details internally.

The Vulnerable Pattern

@Get(':id')
async findOne(@Param('id') id: string) {
  try {
    return await this.userService.findOne(id);
  } catch (error) {
    // VULNERABILITY: Returning the raw error object leaks stack traces and DB internals
    return error;
  }
}

The Secure Implementation

The vulnerable code snippet returns the raw exception object directly to the client. If a database query fails, the attacker might receive a full stack trace or SQL syntax error, facilitating SQL injection or path traversal. The secure implementation uses a Global Exception Filter. This layer intercepts all exceptions, checks if they are standard HTTP errors, and returns a sanitized, structured JSON response. Internal Server Errors (500) are stripped of all technical metadata, ensuring that the attacker gains zero insight into the server's internal state.

// http-exception.filter.ts
import { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus } from '@nestjs/common';
import { Response } from 'express';

@Catch() export class GlobalExceptionFilter implements ExceptionFilter { catch(exception: unknown, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); const status = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;

// Log the actual error for internal debugging, but never send it to the client
console.error(exception);

response.status(status).json({
  statusCode: status,
  message: status === HttpStatus.INTERNAL_SERVER_ERROR ? 'Internal server error' : (exception as any).message,
  timestamp: new Date().toISOString(),
  path: ctx.getRequest().url,
});

} }

// main.ts app.useGlobalFilters(new GlobalExceptionFilter());

System Alert • ID: 7407
Target: NestJS API
Potential Vulnerability

Your NestJS API might be exposed to Improper Error Handling

74% of NestJS apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.