@wisemen/api-error
v0.0.3
Published
This package provides a structured and standardized way to handle API errors within a NestJS application. It is designed to be extensible, easy to use, and to integrate seamlessly with `@nestjs/swagger` for automated API documentation.
Maintainers
Keywords
Readme
API error package for NestJS
This package provides a structured and standardized way to handle API errors within a NestJS application. It is designed to be extensible, easy to use, and to integrate seamlessly with @nestjs/swagger for automated API documentation.
Features
- Standardized Error Classes: A collection of abstract classes for common HTTP errors (
BadRequestApiError,NotFoundApiError,ConflictApiError, etc.), each pre-configured with the correct HTTP status code. - Custom Error Creation: An
ApiErrorbase class that allows you to define your own custom, domain-specific errors. - Rich Error Metadata: Decorators to enrich your errors with unique codes (
@ApiErrorCode) and additional metadata (@ApiErrorMeta). - Swagger Integration: Automatically generate detailed and accurate Swagger documentation for your error responses with decorators like
@ApiNotFoundErrorResponseand@ApiBadRequestErrorResponse. - Type-Safe: Written in TypeScript to ensure full type-safety for your error objects.
Philosophy
The core philosophy is to treat API errors as first-class citizens of your domain. By creating specific, descriptive error classes, you can make your codebase more explicit and easier to understand. This approach ensures that error handling is not an afterthought but a well-defined part of your application's architecture.
This package promotes:
- Clarity: Machine-readable error codes and human-readable details.
- Consistency: A uniform error response structure across all endpoints.
- Discoverability: Automatic Swagger documentation makes it easy for API consumers to understand potential errors.
- Extensibility: Easily create new error types that fit your application's specific needs.
Example
Here's how you can define and use a custom API error.
1. Define a custom error
Create a new class that extends one of the provided base error classes. Use decorators to add a unique code and any relevant metadata.
// src/users/errors/user-not-found.api-error.ts
import { NotFoundApiError } from "@wisemen/api-error";
import { ApiErrorCode } from "@wisemen/api-error";
import { ApiErrorMeta } from "@wisemen/api-error";
class UserNotFoundErrorMeta {
@ApiProperty()
readonly userId: string;
}
@ApiErrorMeta(UserNotFoundErrorMeta)
export class UserNotFoundError extends NotFoundApiError {
@ApiErrorCode("user_not_found")
readonly code: "user_not_found";
constructor(userId: string) {
super(`User with id '${userId}' not found.`);
this.meta = { userId };
}
}2. Use the error in your controller
In your controller, use the custom error and document it with the corresponding response decorator.
// src/users/users.controller.ts
import { Controller, Get, Param } from "@nestjs/common";
import { ApiNotFoundErrorResponse } from "@wisemen/api-error";
import { UserNotFoundError } from "./errors/user-not-found.api-error.ts";
@Controller("users")
export class UsersController {
@Get(":id")
@ApiNotFoundErrorResponse(UserNotFoundError)
async findOne(@Param("id") id: string) {
const user = await this.usersService.findOne(id);
if (!user) {
throw new UserNotFoundError(id);
}
return user;
}
}When a UserNotFoundError is thrown, the client will receive a 404 Not Found response with the following body:
{
"errors": [
{
"status": "404",
"code": "user_not_found",
"detail": "User with id 'some-id' not found.",
"meta": {
"userId": "some-id"
}
}
]
}The Swagger documentation will also be updated to show that this endpoint can return a 404 error with the specified structure.
Deep Dive
The ApiError base class
The abstract ApiError class is the foundation of this package.
export abstract class ApiError extends Error {
abstract readonly code: string;
abstract readonly status: string;
abstract readonly meta: unknown;
readonly detail?: string;
}status: The HTTP status code for the error.code: A unique, machine-readable string identifying the error.detail: A human-readable explanation specific to this occurrence of the problem.meta: An object containing non-standard meta-information about the error.
Decorators
@ApiErrorStatus(status: HttpStatus): Sets thestatusproperty for an error class and makes it a read-only property in the Swagger documentation.@ApiErrorCode(code: string): Sets thecodeproperty for an error class and makes it a read-only property with a specific enum value in the Swagger documentation.@ApiErrorMeta(meta: T): Defines the shape of themetaobject for an error class for Swagger documentation.@ApiErrorResponse(status: HttpStatus, errors: Array<ClassConstructor<ApiError>>): A generic decorator to document one or more errors for a given HTTP status in a controller method.@ApiNotFoundErrorResponse(...),@ApiBadRequestErrorResponse(...),@ApiConflictErrorResponse(...): Convenience decorators that are shortcuts for@ApiErrorResponsewith a pre-filled status code.
