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
mermaidgraph 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
tsimport { 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
UnauthorizedExceptionwhen authentication fails, credentials are missing, or a token is invalid or expired. - Use
ForbiddenExceptioninstead 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)
AuthGuard—integration/graphql-code-first/src/common/guards/auth.guard.ts:9AuthGuard—sample/19-auth-jwt/src/auth/auth.guard.ts:13AuthService—sample/19-auth-jwt/src/auth/auth.service.ts:5UnauthorizedFilter—integration/graphql-code-first/src/common/filters/unauthorized.filter.ts:4
Was this page helpful?