### Install error-lib Package Source: https://github.com/dmanavi/error_lib/blob/master/README.md Install the error-lib package using npm, yarn, or pnpm. ```sh # npm npm install error-lib # yarn yarn add error-lib # pnpm pnpm add error-lib ``` -------------------------------- ### Usage with CommonJS Modules in NodeJS Source: https://github.com/dmanavi/error_lib/blob/master/README.md Import and use custom error classes like NotFoundError and ForbiddenError in NodeJS applications using CommonJS modules. This example demonstrates checking file existence and access, throwing specific errors, and catching them. ```js // for NodeJS applications (Common JS) const { ApplicationError, NotFoundError, ForbiddenError, } = require('error-lib'); // Let's suppose we have a snippet that reads the content of a file // 1) The first step is to check if the file exists. // 2) The second step is to check if current user has access to the file. const checkIfFileExist = (path) => { // 'fs.exists' is a pseudo code if (fs.exists(path) === false) { throw new NotFoundError(`${path} was not found.`); } return true; }; const readFileContent = (path) => { if (fs.hasAccess(path) === false) { throw new ForbiddenError(`User does not have access to '${path}'`); } return 'dummy content'; }; try { // step 1 checkIfFileExist('/path/to/file'); // step 2 const fileContent = readFileContent('/path/to/file'); } catch (err) { if (err instanceof NotFoundError) { // now you have intellisense enabled console.error('File not found!'); } else if (err instanceof ForbiddenError) { // now you have intellisense enabled console.error('No access to the file'); } else { console.error('Something went wrong!'); } } ``` -------------------------------- ### Usage with ES Modules in TypeScript/JavaScript Source: https://github.com/dmanavi/error_lib/blob/master/README.md Import and use custom error classes like NotFoundError and ForbiddenError in TypeScript or JavaScript applications using ES Modules. This example demonstrates checking file existence and access, throwing specific errors, and catching them. ```ts // For typescript/javascript (ES Module) import { ApplicationError, NotFoundError } from 'error-lib'; // Let's suppose we have a snippet that reads the content of a file // 1) The first step is to check if the file exists. // 2) The second step is to check if current user has access to the file. const checkIfFileExist = (path) => { // 'fs.exists' is a pseudo code if (fs.exists(path) === false) { throw new NotFoundError(`${path} was not found.`); } return true; }; const readFileContent = (path) => { if (fs.hasAccess(path) === false) { throw new ForbiddenError(`User does not have access to '${path}'`); } return 'dummy content'; }; try { // step 1 checkIfFileExist('/path/to/file'); // step 2 const fileContent = readFileContent('/path/to/file'); } catch (err) { if (err instanceof NotFoundError) { // now you have intellisense enabled console.error('File not found!'); } else if (err instanceof ForbiddenError) { // now you have intellisense enabled console.error('No access to the file'); } else { console.error('Something went wrong!'); } } ``` -------------------------------- ### Extend BadRequestError in JavaScript Source: https://github.com/dmanavi/error_lib/blob/master/README.md Extend BadRequestError to create a custom InvalidUsernamePassword error. This example shows how to set a custom error code and message, and how to use it in your application. ```javascript // Let's suppose you're adding an InvalidUsernamePassword error (which can be derived from BadRequestError). // invalid_username_password_error.ts const { BadRequestError } = require('error-lib'); class InvalidUsernamePassword extends BadRequestError { /** * * @param message {string} Custom error message * @param opts Extra options */ constructor(message, opts) { message = message ?? 'InvalidUsernamePasswordError'; super(message, { cause: opts?.cause, code: opts?.code ?? 'E_INVALID_USERNAME_PASSWORD', }); Error.captureStackTrace(this, InvalidUsernamePassword); Object.setPrototypeOf(this, InvalidUsernamePassword.prototype); } } module.exports = { InvalidUsernamePassword, }; // in your application (e.g. app.js) // Now you can use your new error class to throw more specific errors if (user !== 'user1' && pass !== 'p4$sw0rd!') { throw new InvalidUsernamePassword(); } ``` -------------------------------- ### Extend BadRequestError in TypeScript Source: https://github.com/dmanavi/error_lib/blob/master/README.md Create a custom InvalidUsernamePassword error by extending BadRequestError in TypeScript. This example includes interface definitions for constructor options and demonstrates usage. ```typescript // Let's suppose you're adding an InvalidUsernamePassword error (which can be derived from BadRequestError). // invalid_username_password_error.ts import { BadRequestError, BadRequestErrorConstructorOptions } from 'error-lib'; export interface InvalidUsernamePasswordConstructorOptions< TCauseError extends Error = Error, > extends BadRequestErrorConstructorOptions {} export class InvalidUsernamePassword< TCause extends Error = Error, > extends BadRequestError { /** * * @param message Custom error message * @param opts Extra options */ constructor( message?: string, opts?: InvalidUsernamePasswordConstructorOptions, ) { message = message ?? 'InvalidUsernamePasswordError'; super(message, { cause: opts?.cause, code: opts?.code ?? 'E_INVALID_USERNAME_PASSWORD', }); Error.captureStackTrace(this, InvalidUsernamePassword); Object.setPrototypeOf(this, InvalidUsernamePassword.prototype); } } // in your application (e.g. app.ts) // Now you can use your new error class to throw more specific errors if (user !== 'user1' && pass !== 'p4$sw0rd!') { throw new InvalidUsernamePassword(); } ``` -------------------------------- ### Using ApplicationError for base error handling Source: https://context7.com/dmanavi/error_lib/llms.txt Demonstrates instantiation, custom codes, error chaining via the cause property, and type-safe catching. ```typescript import { ApplicationError } from 'error-lib'; // Basic usage with default message and code const basicError = new ApplicationError(); console.log(basicError.message); // "ApplicationError" console.log(basicError.code); // "E_APPLICATION_ERROR" // Custom message and code const customError = new ApplicationError('Database connection failed', { code: 'E_DB_CONNECTION' }); console.log(customError.message); // "Database connection failed" console.log(customError.code); // "E_DB_CONNECTION" // Error chaining with cause const originalError = new Error('Connection timeout'); const wrappedError = new ApplicationError('Service unavailable', { code: 'E_SERVICE_UNAVAILABLE', cause: originalError }); console.log(wrappedError.cause); // Error: Connection timeout // Type-safe error handling try { throw new ApplicationError('Something went wrong'); } catch (err) { if (err instanceof ApplicationError) { console.log(`[${err.code}] ${err.message}`); } } ``` -------------------------------- ### Create and Handle NotFoundError Source: https://context7.com/dmanavi/error_lib/llms.txt Use NotFoundError for general 'not found' situations, equivalent to HTTP 404. It has a default code 'E_NOT_FOUND'. ```typescript import { NotFoundError } from 'error-lib'; // Basic not found error const notFound = new NotFoundError(); console.log(notFound.message); // "NotFoundError" console.log(notFound.code); // "E_NOT_FOUND" // File not found scenario function readConfigFile(path: string) { const fileExists = false; // Simulated check if (!fileExists) { throw new NotFoundError(`Configuration file '${path}' was not found`, { code: 'E_CONFIG_NOT_FOUND' }); } } try { readConfigFile('/etc/app/config.json'); } catch (err) { if (err instanceof NotFoundError) { console.log(`[${err.code}] ${err.message}`); // "[E_CONFIG_NOT_FOUND] Configuration file '/etc/app/config.json' was not found" } } ``` -------------------------------- ### Using BadRequestError for HTTP 400 scenarios Source: https://context7.com/dmanavi/error_lib/llms.txt Shows how to use BadRequestError for input validation and standard HTTP error reporting. ```typescript import { BadRequestError } from 'error-lib'; // Basic bad request error const badRequest = new BadRequestError(); console.log(badRequest.message); // "BadRequestError" console.log(badRequest.code); // "E_BAD_REQUEST" // Input validation scenario function processUserInput(input: string) { if (!input || input.trim().length === 0) { throw new BadRequestError('Input cannot be empty', { code: 'E_EMPTY_INPUT' }); } return input.trim(); } try { processUserInput(''); } catch (err) { if (err instanceof BadRequestError) { console.log(`Bad Request: ${err.message}`); // "Bad Request: Input cannot be empty" } } ``` -------------------------------- ### Create and Handle ResourceNotFoundError Source: https://context7.com/dmanavi/error_lib/llms.txt Use ResourceNotFoundError for specific resource lookup failures. It extends NotFoundError and includes resourceId and resourceType properties. ```typescript import { ResourceNotFoundError, NotFoundError } from 'error-lib'; // Basic resource not found with auto-generated message const productError = new ResourceNotFoundError('123', 'Product'); console.log(productError.message); // "ResourceNotFoundError: No Product found having identifier '123'" console.log(productError.code); // "E_RESOURCE_NOT_FOUND" console.log(productError.resourceId); // "123" console.log(productError.resourceType); // "Product" // Database lookup scenario interface User { id: string; name: string; } const users: User[] = [{ id: '1', name: 'Alice' }]; function getUserById(id: string): User { const user = users.find(u => u.id === id); if (!user) { throw new ResourceNotFoundError(id, 'User', undefined, { code: 'E_USER_NOT_FOUND' }); } return user; } try { getUserById('999'); } catch (err) { if (err instanceof ResourceNotFoundError) { console.log(`${err.resourceType} with ID '${err.resourceId}' not found`); // "User with ID '999' not found" } } // Typed resource identifiers const typedError = new ResourceNotFoundError(42, 'Order'); console.log(typedError.resourceId); // 42 (typed as number) console.log(typedError.resourceType); // "Order" (typed as string) ``` -------------------------------- ### Create Custom Error Classes Source: https://context7.com/dmanavi/error_lib/llms.txt Extend base error classes to define application-specific errors. Ensure proper stack trace capture and prototype setting for instanceof checks to function correctly. ```typescript import { BadRequestError, BadRequestErrorConstructorOptions } from 'error-lib'; // Custom error interface interface InvalidCredentialsOptions extends BadRequestErrorConstructorOptions {} // Custom error class class InvalidCredentialsError extends BadRequestError { constructor( message?: string, opts?: InvalidCredentialsOptions ) { message = message ?? 'Invalid username or password'; super(message, { cause: opts?.cause, code: opts?.code ?? 'E_INVALID_CREDENTIALS' }); Error.captureStackTrace(this, InvalidCredentialsError); Object.setPrototypeOf(this, InvalidCredentialsError.prototype); } } // Usage function authenticate(username: string, password: string) { if (username !== 'admin' || password !== 'secret') { throw new InvalidCredentialsError(); } return { token: 'jwt-token' }; } try { authenticate('user', 'wrong'); } catch (err) { if (err instanceof InvalidCredentialsError) { console.log(err.code); // "E_INVALID_CREDENTIALS" console.log(err.message); // "Invalid username or password" } if (err instanceof BadRequestError) { console.log('Is also a BadRequestError'); // true } } ``` -------------------------------- ### Create and Handle ForbiddenError Source: https://context7.com/dmanavi/error_lib/llms.txt Use ForbiddenError for access denied scenarios, equivalent to HTTP 403. It extends ApplicationError with a default code 'E_FORBIDDEN'. ```typescript import { ForbiddenError } from 'error-lib'; // Basic forbidden error const forbidden = new ForbiddenError(); console.log(forbidden.message); // "ForbiddenError" console.log(forbidden.code); // "E_FORBIDDEN" // Access control scenario interface User { id: string; role: 'admin' | 'user'; } function deleteUser(currentUser: User, targetUserId: string) { if (currentUser.role !== 'admin') { throw new ForbiddenError('Only administrators can delete users', { code: 'E_INSUFFICIENT_PERMISSIONS' }); } // Perform deletion... } try { deleteUser({ id: '1', role: 'user' }, '2'); } catch (err) { if (err instanceof ForbiddenError) { console.log(`Access Denied: ${err.message}`); // "Access Denied: Only administrators can delete users" } } // File access scenario function readSecureFile(path: string, hasAccess: boolean) { if (!hasAccess) { throw new ForbiddenError(`User does not have access to '${path}'`, { code: 'E_FILE_ACCESS_DENIED' }); } return 'file content'; } ``` -------------------------------- ### Using ValidationError for structured validation failures Source: https://context7.com/dmanavi/error_lib/llms.txt Illustrates handling validation details and verifying the inheritance chain of the error class. ```typescript import { ValidationError, BadRequestError, ApplicationError } from 'error-lib'; // Basic validation error const validationErr = new ValidationError({ field: 'email', issue: 'invalid format' }); console.log(validationErr.code); // "E_VALIDATION_FAILED" console.log(validationErr.validationError); // { field: 'email', issue: 'invalid format' } // Form validation example interface FieldError { field: string; message: string; } function validateForm(data: { email?: string; password?: string }) { const errors: FieldError[] = []; if (!data.email?.includes('@')) { errors.push({ field: 'email', message: 'Invalid email format' }); } if (!data.password || data.password.length < 8) { errors.push({ field: 'password', message: 'Password must be at least 8 characters' }); } if (errors.length > 0) { throw new ValidationError(errors, 'Form validation failed', { code: 'E_FORM_VALIDATION' }); } } try { validateForm({ email: 'invalid', password: '123' }); } catch (err) { if (err instanceof ValidationError) { console.log(err.validationError); // [{ field: 'email', message: 'Invalid email format' }, { field: 'password', message: 'Password must be at least 8 characters' }] } } // Inheritance check const ve = new ValidationError([]); console.log(ve instanceof BadRequestError); // true console.log(ve instanceof ApplicationError); // true console.log(ve instanceof Error); // true ``` -------------------------------- ### Create and Handle RouteNotFoundError Source: https://context7.com/dmanavi/error_lib/llms.txt Use RouteNotFoundError for API route mismatches. It extends NotFoundError and includes route and method properties for HTTP context. ```typescript import { RouteNotFoundError } from 'error-lib'; // Route with method const routeErr = new RouteNotFoundError('/api/products', 'GET'); console.log(routeErr.message); // "RouteNotFoundError: Route 'GET: /api/products' was not found" console.log(routeErr.code); // "E_ROUTE_NOT_FOUND" console.log(routeErr.route); // "/api/products" console.log(routeErr.method); // "GET" // Route without method const routeOnly = new RouteNotFoundError('/api/unknown'); console.log(routeOnly.message); // "RouteNotFoundError: Route '/api/unknown' was not found" // Express middleware example function notFoundHandler(req: { method: string; path: string }, res: any, next: any) { throw new RouteNotFoundError(req.path, req.method, undefined, { code: 'E_ENDPOINT_NOT_FOUND' }); } // Custom message const customRouteErr = new RouteNotFoundError('/v2/legacy', 'POST', 'This API version is deprecated'); console.log(customRouteErr.message); // "This API version is deprecated" ``` -------------------------------- ### Normalize Error Objects for Serialization Source: https://context7.com/dmanavi/error_lib/llms.txt Use normalizeErrorObject to strip non-serializable properties from error instances. This is essential for safely sending error details in API responses or logging. ```typescript import { normalizeErrorObject, ApplicationError, ResourceNotFoundError } from 'error-lib'; // Normalize basic error const error = new ApplicationError('Something failed', { code: 'E_FAILURE' }); const normalized = normalizeErrorObject(error); console.log(JSON.stringify(normalized, null, 2)); // { // "message": "Something failed", // "code": "E_FAILURE", // "stack": "Error: Something failed\n at ..." // } // Normalize error with cause for API response const dbError = new Error('Connection refused'); const appError = new ResourceNotFoundError('user-123', 'User', undefined, { cause: dbError }); const serializable = normalizeErrorObject(appError); console.log(JSON.stringify(serializable)); // All properties including resourceId, resourceType, and cause are preserved // Express error handler example function errorHandler(err: Error, req: any, res: any, next: any) { const normalizedError = normalizeErrorObject(err); if (err instanceof ApplicationError) { res.status(400).json({ success: false, error: normalizedError }); } else { res.status(500).json({ success: false, error: { message: 'Internal Server Error' } }); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.