UNPKG

jsm-exceptions

Version:

A comprehensive TypeScript exception library with HTTP status code support, detailed JSDoc documentation, and backward compatibility. Provides structured error handling for web applications and APIs.

83 lines (82 loc) 3.11 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const joi_1 = __importDefault(require("joi")); const base_exception_1 = __importDefault(require("./base.exception")); /** * @fileoverview Validation exception (HTTP 422) * @author dr. Salmi <reevosolutions@gmail.com> */ /** * Exception thrown when input validation fails. * Corresponds to HTTP 422 Unprocessable Entity status code. * Supports both Joi validation errors and custom field errors. * * @class ValidationException * @extends {BaseException} * @example * ```typescript * // With custom field errors * throw new ValidationException('Validation failed', { * email: { value: 'invalid-email', message: 'Email format is invalid' } * }); * * // With Joi validation error * throw new ValidationException('Validation failed', joiValidationError); * ``` */ class ValidationException extends base_exception_1.default { /** * Creates an instance of ValidationException. * * @param {string} [message='Validation failed'] - The error message * @param {ErrorFields | Joi.ValidationError} [fields={}] - Field errors or Joi validation error * @param {Record<string, any>} [context] - Additional context * @memberof ValidationException */ constructor(message = 'Validation failed', fields = {}, context) { super(message, 422, context); /** * Indicates if this exception was created from a Joi validation error * @type {boolean} */ this.isJoi = false; /** * Indicates if this exception was created from a Mongoose validation error * @type {boolean} */ this.isMongoose = false; /** * Indicates if this exception was created from a Celebrate validation error * @type {boolean} */ this.isCelebrate = false; if (fields instanceof joi_1.default.ValidationError) { Object.defineProperty(this, 'isJoi', { value: true, writable: false }); this.fields = fields.details.reduce((acc, curr) => { var _a; const key = Array.isArray(curr.path) ? curr.path[0] : curr.path; acc[key] = { value: ((_a = curr.context) === null || _a === void 0 ? void 0 : _a.value) || undefined, message: curr.message }; return acc; }, {}); } else { this.fields = fields; } } /** * Returns a JSON representation of the validation exception * * @returns {object} JSON representation including field errors * @memberof ValidationException */ toJSON() { return Object.assign(Object.assign({}, super.toJSON()), { name: this.constructor.name, fields: this.fields, isJoi: this.isJoi, isMongoose: this.isMongoose, isCelebrate: this.isCelebrate }); } } exports.default = ValidationException;