Skip to content

UnauthorizedException

reference
1 min readUpdated

Kind: Class

Source: packages/common/exceptions/unauthorized.exception.ts

Part of: Common

Defines an HTTP exception for Unauthorized type errors.

UnauthorizedException represents an HTTP 401 error, indicating that a request cannot be authenticated or lacks valid credentials. It extends the framework's HTTP exception model so authentication guards, controllers, and global exception filters can return a consistent unauthorized response.

Extends: HttpException

Diagram

mermaid
graph LR
  Client[Client Request] --> Guard[Authentication Guard]
  Guard -->|Missing or invalid credentials| Exception[UnauthorizedException]
  Exception --> Filter[HTTP Exception Filter]
  Filter --> Response[HTTP 401 Unauthorized Response]

Usage

ts
import { UnauthorizedException } from '@nestjs/common';

function validateAccessToken(token?: string) {
  if (!token || token !== process.env.API_ACCESS_TOKEN) {
    throw new UnauthorizedException('Invalid or missing access token');
  }

  return { authenticated: true };
}

AI Coding Instructions

  • Throw UnauthorizedException when authentication fails, credentials are missing, or a token is invalid or expired.
  • Use ForbiddenException instead when the user is authenticated but does not have permission for the requested resource.
  • Provide a safe, client-facing error message; never include tokens, passwords, or internal authentication details.
  • Prefer throwing this exception from authentication guards or validation services so controllers remain focused on request handling.

Used by

4 references from 4 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example.

Imported by (4)

  • AuthGuardintegration/graphql-code-first/src/common/guards/auth.guard.ts:9
  • AuthGuardsample/19-auth-jwt/src/auth/auth.guard.ts:13
  • AuthServicesample/19-auth-jwt/src/auth/auth.service.ts:5
  • UnauthorizedFilterintegration/graphql-code-first/src/common/filters/unauthorized.filter.ts:4

Was this page helpful?

Download as PDF
UnauthorizedException — NestJS head-to-head