# Exception Handling — NestJS: Building Scalable Node.js APIs

Source: https://www.skillbyai.com/en/nestjs/nestjs-exception-handling

> Throw built-in HTTP exceptions and format errors consistently with a global exception filter.

## Built-in exceptions

NestJS provides `BadRequestException`, `NotFoundException`, `UnauthorizedException`, etc. that automatically set the right HTTP status.

```typescript
import { NotFoundException, BadRequestException } from '@nestjs/common';

@Get(':id')
findOne(@Param('id') id: string) {
  const user = this.usersService.findOne(id);
  if (!user) {
    throw new NotFoundException(`User ${id} not found`);
  }
  return user;
}
```

## Global exception filter

Implement `ExceptionFilter` to catch and format errors globally across your app.

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

    response.status(status).json({
      statusCode: status,
      message: exception instanceof Error ? exception.message : 'Internal error'
    });
  }
}

// app.useGlobalFilters(new AllExceptionsFilter());
```

## Throwing HTTP exceptions

Throw a built-in exception and Nest builds the response.

- `NotFoundException` maps to status 404.
- The message you pass becomes the `message` field.

```ts
import { Controller, Get, NotFoundException, Param } from '@nestjs/common';

@Controller('books')
export class BooksController {
  @Get(':id')
  find(@Param('id') id: string) {
    throw new NotFoundException(`Book ${id} not found`);
  }
}
```

Output:

```
{"message":"Book 5 not found","error":"Not Found","statusCode":404}
```

Quick check

**Quiz:** What does `@Catch()` with no arguments on an exception filter catch?

- [ ] Only HttpException
- [x] Every thrown exception
- [ ] Only validation errors

*Answer:* Every thrown exception. An empty `@Catch()` is a catch-all filter for any exception type.
