@asaidimu/utils-error 1.0.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.mts CHANGED
@@ -187,7 +187,7 @@ declare class SystemError extends Error {
187
187
  readonly path?: string;
188
188
  readonly operation?: string;
189
189
  readonly issues: readonly Issue[];
190
- readonly cause?: unknown;
190
+ readonly cause?: unknown | unknown[];
191
191
  constructor(params: {
192
192
  code: string;
193
193
  message?: string;
@@ -195,7 +195,7 @@ declare class SystemError extends Error {
195
195
  path?: string;
196
196
  operation?: string;
197
197
  issues?: readonly Issue[];
198
- cause?: unknown;
198
+ cause?: unknown | unknown[];
199
199
  metadata?: Partial<Omit<ErrorCodeMetadata, "code">>;
200
200
  });
201
201
  /**
@@ -217,15 +217,27 @@ declare class SystemError extends Error {
217
217
  /**
218
218
  * Returns a new SystemError wrapping the specified cause.
219
219
  */
220
- withCause(cause: unknown): SystemError;
220
+ withCause(cause: unknown | unknown[]): SystemError;
221
221
  /**
222
222
  * Returns the HTTP status code for this error (if applicable).
223
223
  */
224
224
  getHttpStatus(): number | undefined;
225
225
  /**
226
- * Formats the error for logging with structured metadata.
226
+ * Recursively extracts errors and builds a chronological chain (deepest leaf first).
227
+ */
228
+ private extractChronologicalChain;
229
+ /**
230
+ * Formats the error for logging with an inverted, chronological execution path.
227
231
  */
228
232
  toLogEntry(): Record<string, unknown>;
233
+ /**
234
+ * Helper to recursively serialize any cause (single error, system error, or an array of them)
235
+ */
236
+ private serializeCause;
237
+ /**
238
+ * Automatically invoked by JSON.stringify().
239
+ */
240
+ toJSON(): Record<string, unknown>;
229
241
  /**
230
242
  * Produces a human-readable representation suitable for logging.
231
243
  */
package/index.d.ts CHANGED
@@ -187,7 +187,7 @@ declare class SystemError extends Error {
187
187
  readonly path?: string;
188
188
  readonly operation?: string;
189
189
  readonly issues: readonly Issue[];
190
- readonly cause?: unknown;
190
+ readonly cause?: unknown | unknown[];
191
191
  constructor(params: {
192
192
  code: string;
193
193
  message?: string;
@@ -195,7 +195,7 @@ declare class SystemError extends Error {
195
195
  path?: string;
196
196
  operation?: string;
197
197
  issues?: readonly Issue[];
198
- cause?: unknown;
198
+ cause?: unknown | unknown[];
199
199
  metadata?: Partial<Omit<ErrorCodeMetadata, "code">>;
200
200
  });
201
201
  /**
@@ -217,15 +217,27 @@ declare class SystemError extends Error {
217
217
  /**
218
218
  * Returns a new SystemError wrapping the specified cause.
219
219
  */
220
- withCause(cause: unknown): SystemError;
220
+ withCause(cause: unknown | unknown[]): SystemError;
221
221
  /**
222
222
  * Returns the HTTP status code for this error (if applicable).
223
223
  */
224
224
  getHttpStatus(): number | undefined;
225
225
  /**
226
- * Formats the error for logging with structured metadata.
226
+ * Recursively extracts errors and builds a chronological chain (deepest leaf first).
227
+ */
228
+ private extractChronologicalChain;
229
+ /**
230
+ * Formats the error for logging with an inverted, chronological execution path.
227
231
  */
228
232
  toLogEntry(): Record<string, unknown>;
233
+ /**
234
+ * Helper to recursively serialize any cause (single error, system error, or an array of them)
235
+ */
236
+ private serializeCause;
237
+ /**
238
+ * Automatically invoked by JSON.stringify().
239
+ */
240
+ toJSON(): Record<string, unknown>;
229
241
  /**
230
242
  * Produces a human-readable representation suitable for logging.
231
243
  */
package/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e={VALIDATION_FAILED:{code:"VAL-001",name:"VALIDATION_FAILED",description:"Input validation failed due to one or more invalid fields",category:"validation",httpStatus:400,logLevel:"warn"},REQUIRED_FIELD_MISSING:{code:"VAL-002",name:"REQUIRED_FIELD_MISSING",description:"A required field was not provided in the request",category:"validation",httpStatus:400,logLevel:"warn"},INVALID_FORMAT:{code:"VAL-003",name:"INVALID_FORMAT",description:"Field value does not match expected format",category:"validation",httpStatus:400,logLevel:"warn"},NOT_FOUND:{code:"DB-001-NF",name:"NOT_FOUND",description:"The requested resource could not be found",category:"database",httpStatus:404,logLevel:"info",action:"Verify the resource identifier exists before accessing"},DUPLICATE_KEY:{code:"DB-002-DUP",name:"DUPLICATE_KEY",description:"A unique constraint violation occurred",category:"database",httpStatus:409,logLevel:"warn",action:"Check if the resource already exists before creation"},RESOURCE_LOCKED:{code:"DB-003-LOCK",name:"RESOURCE_LOCKED",description:"The resource is currently locked by another operation",category:"database",httpStatus:409,logLevel:"warn",action:"Retry the operation after a brief delay"},PERMISSION_DENIED:{code:"AUTH-001-DENIED",name:"PERMISSION_DENIED",description:"The authenticated user lacks permission for this operation",category:"auth",httpStatus:403,logLevel:"warn",action:"Check user roles and permissions"},UNAUTHENTICATED:{code:"AUTH-002-UNAUTH",name:"UNAUTHENTICATED",description:"Authentication is required for this operation",category:"auth",httpStatus:401,logLevel:"info",action:"Provide valid authentication credentials"},INVALID_COMMAND:{code:"BUS-001",name:"INVALID_COMMAND",description:"The command or operation is invalid for the current state",category:"business",httpStatus:400,logLevel:"warn"},OPERATION_ABORTED:{code:"BUS-002-ABORT",name:"OPERATION_ABORTED",description:"The operation was explicitly aborted",category:"business",httpStatus:409,logLevel:"info"},INTERNAL_ERROR:{code:"SYS-001",name:"INTERNAL_ERROR",description:"An unexpected internal error occurred",category:"system",httpStatus:500,logLevel:"error",action:"Check system logs for stack traces and diagnostic information"},BACKEND_ERROR:{code:"SYS-002",name:"BACKEND_ERROR",description:"An error occurred in a backend service",category:"system",httpStatus:502,logLevel:"error"},CONCURRENCY_ERROR:{code:"CON-001",name:"CONCURRENCY_ERROR",description:"A concurrency conflict occurred during the operation",category:"concurrency",httpStatus:409,logLevel:"warn",action:"Retry the operation with updated data"}},t=new Map;function s(s){const a=Object.values(e).find((e=>e.code===s));if(a)return a;const r=t.get(s);return r||{code:s,name:s.replace(/-/g,"_"),description:`Unknown error: ${s}`,category:"custom",httpStatus:500,logLevel:"error",action:"Check if this error code is properly registered or handle as unknown error"}}var a=class e extends Error{code;codeMetadata;severity;path;operation;issues;cause;constructor(t){const a={...s(t.code),...t.metadata,code:t.code};super(t.message??a.description),this.name="SystemError",this.code=t.code,this.codeMetadata=a,this.severity=t.severity??"error",this.path=t.path,this.operation=t.operation,this.issues=t.issues??[],this.cause=t.cause,Object.setPrototypeOf(this,e.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,e)}withPath(t){return new e({code:this.code,message:this.message,severity:this.severity,path:t,operation:this.operation,issues:this.issues,cause:this.cause,metadata:this.codeMetadata})}withOperation(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:t,issues:this.issues,cause:this.cause,metadata:this.codeMetadata})}withIssue(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,issues:[...this.issues,t],cause:this.cause,metadata:this.codeMetadata})}withIssues(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,issues:[...this.issues,...t],cause:this.cause,metadata:this.codeMetadata})}withCause(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,issues:this.issues,cause:t,metadata:this.codeMetadata})}getHttpStatus(){return this.codeMetadata.httpStatus}toLogEntry(){return{name:this.name,code:this.code,category:this.codeMetadata.category,message:this.message,path:this.path,operation:this.operation,issues:this.issues,cause:this.cause instanceof Error?this.cause.message:this.cause,stack:this.stack,timestamp:(new Date).toISOString()}}toString(){let e=`[${this.code}] ${this.message} (${this.codeMetadata.category})`;return this.path&&(e+=` at '${this.path}'`),this.operation&&(e+=` during '${this.operation}'`),this.issues.length>0&&(e+="\nIssues:\n"+this.issues.map(((e,t)=>` ${t+1}. ${e.message} [${e.code}]`)).join("\n")),this.cause&&(e+=`\nCause: ${this.cause instanceof Error?this.cause.message:String(this.cause)}`),e}};var r={NOT_FOUND:"DB-001-NF",DUPLICATE_KEY:"DB-002-DUP",INVALID_COMMAND:"BUS-001",PERMISSION_DENIED:"AUTH-001-DENIED",BACKEND_ERROR:"SYS-002",INTERNAL_ERROR:"SYS-001",VALIDATION_FAILED:"VAL-001",CONCURRENCY_ERROR:"CON-001",RESOURCE_LOCKED:"DB-003-LOCK",OPERATION_ABORTED:"BUS-002-ABORT"},o={notFound:(e,t)=>new a({code:r.NOT_FOUND,message:t,path:e}),duplicateKey:(e,t)=>new a({code:r.DUPLICATE_KEY,message:t,path:e}),permissionDenied:(e,t)=>new a({code:r.PERMISSION_DENIED,message:t,operation:e}),validationFailed:(e,t)=>new a({code:r.VALIDATION_FAILED,issues:e,path:t}),internalError:(e,t)=>new a({code:r.INTERNAL_ERROR,message:t,cause:e})};exports.CommonErrors=r,exports.ErrorCodes=e,exports.Errors=o,exports.Result={ok:e=>({ok:!0,value:e}),fail:e=>({ok:!1,error:e})},exports.SystemError=a,exports.createError=function(e,t){return new a({code:e,message:t})},exports.error=function(e,t){return new a({code:e,message:t})},exports.getErrorMetadata=s,exports.isKnownErrorCode=function(s){return Object.values(e).some((e=>e.code===s))||t.has(s)},exports.registerErrorCode=function(s){if(Object.values(e).find((e=>e.code===s.code)))throw new Error(`Cannot register custom error code "${s.code}": already exists as built-in error`);if(t.has(s.code))throw new Error(`Custom error code "${s.code}" is already registered`);t.set(s.code,s)};
1
+ "use strict";var e={VALIDATION_FAILED:{code:"VAL-001",name:"VALIDATION_FAILED",description:"Input validation failed due to one or more invalid fields",category:"validation",httpStatus:400,logLevel:"warn"},REQUIRED_FIELD_MISSING:{code:"VAL-002",name:"REQUIRED_FIELD_MISSING",description:"A required field was not provided in the request",category:"validation",httpStatus:400,logLevel:"warn"},INVALID_FORMAT:{code:"VAL-003",name:"INVALID_FORMAT",description:"Field value does not match expected format",category:"validation",httpStatus:400,logLevel:"warn"},NOT_FOUND:{code:"DB-001-NF",name:"NOT_FOUND",description:"The requested resource could not be found",category:"database",httpStatus:404,logLevel:"info",action:"Verify the resource identifier exists before accessing"},DUPLICATE_KEY:{code:"DB-002-DUP",name:"DUPLICATE_KEY",description:"A unique constraint violation occurred",category:"database",httpStatus:409,logLevel:"warn",action:"Check if the resource already exists before creation"},RESOURCE_LOCKED:{code:"DB-003-LOCK",name:"RESOURCE_LOCKED",description:"The resource is currently locked by another operation",category:"database",httpStatus:409,logLevel:"warn",action:"Retry the operation after a brief delay"},PERMISSION_DENIED:{code:"AUTH-001-DENIED",name:"PERMISSION_DENIED",description:"The authenticated user lacks permission for this operation",category:"auth",httpStatus:403,logLevel:"warn",action:"Check user roles and permissions"},UNAUTHENTICATED:{code:"AUTH-002-UNAUTH",name:"UNAUTHENTICATED",description:"Authentication is required for this operation",category:"auth",httpStatus:401,logLevel:"info",action:"Provide valid authentication credentials"},INVALID_COMMAND:{code:"BUS-001",name:"INVALID_COMMAND",description:"The command or operation is invalid for the current state",category:"business",httpStatus:400,logLevel:"warn"},OPERATION_ABORTED:{code:"BUS-002-ABORT",name:"OPERATION_ABORTED",description:"The operation was explicitly aborted",category:"business",httpStatus:409,logLevel:"info"},INTERNAL_ERROR:{code:"SYS-001",name:"INTERNAL_ERROR",description:"An unexpected internal error occurred",category:"system",httpStatus:500,logLevel:"error",action:"Check system logs for stack traces and diagnostic information"},BACKEND_ERROR:{code:"SYS-002",name:"BACKEND_ERROR",description:"An error occurred in a backend service",category:"system",httpStatus:502,logLevel:"error"},CONCURRENCY_ERROR:{code:"CON-001",name:"CONCURRENCY_ERROR",description:"A concurrency conflict occurred during the operation",category:"concurrency",httpStatus:409,logLevel:"warn",action:"Retry the operation with updated data"}},t=new Map;function s(s){const a=Object.values(e).find(e=>e.code===s);if(a)return a;const r=t.get(s);return r||{code:s,name:s.replace(/-/g,"_"),description:`Unknown error: ${s}`,category:"custom",httpStatus:500,logLevel:"error",action:"Check if this error code is properly registered or handle as unknown error"}}var a=class e extends Error{code;codeMetadata;severity;path;operation;issues;cause;constructor(t){const a={...s(t.code),...t.metadata,code:t.code};super(t.message??a.description),this.name="SystemError",this.code=t.code,this.codeMetadata=a,this.severity=t.severity??"error",this.path=t.path,this.operation=t.operation,this.issues=t.issues??[],this.cause=t.cause,Object.setPrototypeOf(this,e.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,e)}withPath(t){return new e({code:this.code,message:this.message,severity:this.severity,path:t,operation:this.operation,issues:this.issues,cause:this.cause,metadata:this.codeMetadata})}withOperation(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:t,issues:this.issues,cause:this.cause,metadata:this.codeMetadata})}withIssue(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,issues:[...this.issues,t],cause:this.cause,metadata:this.codeMetadata})}withIssues(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,issues:[...this.issues,...t],cause:this.cause,metadata:this.codeMetadata})}withCause(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,issues:this.issues,cause:t,metadata:this.codeMetadata})}getHttpStatus(){return this.codeMetadata.httpStatus}extractChronologicalChain(e){if(!e)return[];if(Array.isArray(e))return e.flatMap(e=>this.extractChronologicalChain(e));if(e instanceof AggregateError)return e.errors.flatMap(e=>this.extractChronologicalChain(e));let t={name:e instanceof Error?e.name:"UnknownError",message:e instanceof Error?e.message:"object"==typeof e&&null!==e?JSON.stringify(e):String(e),code:e?.code,operation:e?.operation};if(!(e instanceof Error)&&"object"==typeof e&&null!==e){const t=Object.keys(e);if(1===t.length&&"object"==typeof e[t[0]])return this.extractChronologicalChain(e[t[0]])}const s=e?.cause;return s?[...this.extractChronologicalChain(s),t]:[t]}toLogEntry(){const e=this.extractChronologicalChain(this.cause);e.push({name:this.name,message:this.message,code:this.code,operation:this.operation});const t=e.map(e=>`${e.operation||e.code||e.name} (${e.message})`).join(" --\x3e ");return{name:this.name,code:this.code,category:this.codeMetadata.category,severity:this.severity,message:`${this.message} | Failure Path: ${t}`,operation:this.operation,path:this.path,issues:this.issues,history:e,stack:this.stack,timestamp:(new Date).toISOString()}}serializeCause(e){return e?Array.isArray(e)?e.map(e=>this.serializeCause(e)):e instanceof AggregateError?{name:e.name,message:e.message,errors:e.errors.map(e=>this.serializeCause(e)),stack:e.stack}:e instanceof Error?"function"==typeof e.toJSON?e.toJSON():{name:e.name,message:e.message,stack:e.stack}:e:e}toJSON(){return{name:this.name,code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,codeMetadata:this.codeMetadata,issues:this.issues,cause:this.serializeCause(this.cause)}}toString(){let e=`[${this.code}] ${this.message} (${this.codeMetadata.category})`;return this.path&&(e+=` at '${this.path}'`),this.operation&&(e+=` during '${this.operation}'`),this.issues.length>0&&(e+="\nIssues:\n"+this.issues.map((e,t)=>` ${t+1}. ${e.message} [${e.code}]`).join("\n")),this.cause&&(e+=`\nCause: ${this.cause instanceof Error?this.cause.message:String(this.cause)}`),e}};var r={NOT_FOUND:"DB-001-NF",DUPLICATE_KEY:"DB-002-DUP",INVALID_COMMAND:"BUS-001",PERMISSION_DENIED:"AUTH-001-DENIED",BACKEND_ERROR:"SYS-002",INTERNAL_ERROR:"SYS-001",VALIDATION_FAILED:"VAL-001",CONCURRENCY_ERROR:"CON-001",RESOURCE_LOCKED:"DB-003-LOCK",OPERATION_ABORTED:"BUS-002-ABORT"},o={notFound:(e,t)=>new a({code:r.NOT_FOUND,message:t,path:e}),duplicateKey:(e,t)=>new a({code:r.DUPLICATE_KEY,message:t,path:e}),permissionDenied:(e,t)=>new a({code:r.PERMISSION_DENIED,message:t,operation:e}),validationFailed:(e,t)=>new a({code:r.VALIDATION_FAILED,issues:e,path:t}),internalError:(e,t)=>new a({code:r.INTERNAL_ERROR,message:t,cause:e})};exports.CommonErrors=r,exports.ErrorCodes=e,exports.Errors=o,exports.Result={ok:e=>({ok:!0,value:e}),fail:e=>({ok:!1,error:e})},exports.SystemError=a,exports.createError=function(e,t){return new a({code:e,message:t})},exports.error=function(e,t){return new a({code:e,message:t})},exports.getErrorMetadata=s,exports.isKnownErrorCode=function(s){return Object.values(e).some(e=>e.code===s)||t.has(s)},exports.registerErrorCode=function(s){if(Object.values(e).find(e=>e.code===s.code))throw new Error(`Cannot register custom error code "${s.code}": already exists as built-in error`);if(t.has(s.code))throw new Error(`Custom error code "${s.code}" is already registered`);t.set(s.code,s)};
package/index.mjs CHANGED
@@ -1 +1 @@
1
- var e={VALIDATION_FAILED:{code:"VAL-001",name:"VALIDATION_FAILED",description:"Input validation failed due to one or more invalid fields",category:"validation",httpStatus:400,logLevel:"warn"},REQUIRED_FIELD_MISSING:{code:"VAL-002",name:"REQUIRED_FIELD_MISSING",description:"A required field was not provided in the request",category:"validation",httpStatus:400,logLevel:"warn"},INVALID_FORMAT:{code:"VAL-003",name:"INVALID_FORMAT",description:"Field value does not match expected format",category:"validation",httpStatus:400,logLevel:"warn"},NOT_FOUND:{code:"DB-001-NF",name:"NOT_FOUND",description:"The requested resource could not be found",category:"database",httpStatus:404,logLevel:"info",action:"Verify the resource identifier exists before accessing"},DUPLICATE_KEY:{code:"DB-002-DUP",name:"DUPLICATE_KEY",description:"A unique constraint violation occurred",category:"database",httpStatus:409,logLevel:"warn",action:"Check if the resource already exists before creation"},RESOURCE_LOCKED:{code:"DB-003-LOCK",name:"RESOURCE_LOCKED",description:"The resource is currently locked by another operation",category:"database",httpStatus:409,logLevel:"warn",action:"Retry the operation after a brief delay"},PERMISSION_DENIED:{code:"AUTH-001-DENIED",name:"PERMISSION_DENIED",description:"The authenticated user lacks permission for this operation",category:"auth",httpStatus:403,logLevel:"warn",action:"Check user roles and permissions"},UNAUTHENTICATED:{code:"AUTH-002-UNAUTH",name:"UNAUTHENTICATED",description:"Authentication is required for this operation",category:"auth",httpStatus:401,logLevel:"info",action:"Provide valid authentication credentials"},INVALID_COMMAND:{code:"BUS-001",name:"INVALID_COMMAND",description:"The command or operation is invalid for the current state",category:"business",httpStatus:400,logLevel:"warn"},OPERATION_ABORTED:{code:"BUS-002-ABORT",name:"OPERATION_ABORTED",description:"The operation was explicitly aborted",category:"business",httpStatus:409,logLevel:"info"},INTERNAL_ERROR:{code:"SYS-001",name:"INTERNAL_ERROR",description:"An unexpected internal error occurred",category:"system",httpStatus:500,logLevel:"error",action:"Check system logs for stack traces and diagnostic information"},BACKEND_ERROR:{code:"SYS-002",name:"BACKEND_ERROR",description:"An error occurred in a backend service",category:"system",httpStatus:502,logLevel:"error"},CONCURRENCY_ERROR:{code:"CON-001",name:"CONCURRENCY_ERROR",description:"A concurrency conflict occurred during the operation",category:"concurrency",httpStatus:409,logLevel:"warn",action:"Retry the operation with updated data"}},t=new Map;function s(s){if(Object.values(e).find((e=>e.code===s.code)))throw new Error(`Cannot register custom error code "${s.code}": already exists as built-in error`);if(t.has(s.code))throw new Error(`Custom error code "${s.code}" is already registered`);t.set(s.code,s)}function a(s){const a=Object.values(e).find((e=>e.code===s));if(a)return a;const o=t.get(s);return o||{code:s,name:s.replace(/-/g,"_"),description:`Unknown error: ${s}`,category:"custom",httpStatus:500,logLevel:"error",action:"Check if this error code is properly registered or handle as unknown error"}}function o(s){return Object.values(e).some((e=>e.code===s))||t.has(s)}var i=class e extends Error{code;codeMetadata;severity;path;operation;issues;cause;constructor(t){const s={...a(t.code),...t.metadata,code:t.code};super(t.message??s.description),this.name="SystemError",this.code=t.code,this.codeMetadata=s,this.severity=t.severity??"error",this.path=t.path,this.operation=t.operation,this.issues=t.issues??[],this.cause=t.cause,Object.setPrototypeOf(this,e.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,e)}withPath(t){return new e({code:this.code,message:this.message,severity:this.severity,path:t,operation:this.operation,issues:this.issues,cause:this.cause,metadata:this.codeMetadata})}withOperation(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:t,issues:this.issues,cause:this.cause,metadata:this.codeMetadata})}withIssue(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,issues:[...this.issues,t],cause:this.cause,metadata:this.codeMetadata})}withIssues(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,issues:[...this.issues,...t],cause:this.cause,metadata:this.codeMetadata})}withCause(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,issues:this.issues,cause:t,metadata:this.codeMetadata})}getHttpStatus(){return this.codeMetadata.httpStatus}toLogEntry(){return{name:this.name,code:this.code,category:this.codeMetadata.category,message:this.message,path:this.path,operation:this.operation,issues:this.issues,cause:this.cause instanceof Error?this.cause.message:this.cause,stack:this.stack,timestamp:(new Date).toISOString()}}toString(){let e=`[${this.code}] ${this.message} (${this.codeMetadata.category})`;return this.path&&(e+=` at '${this.path}'`),this.operation&&(e+=` during '${this.operation}'`),this.issues.length>0&&(e+="\nIssues:\n"+this.issues.map(((e,t)=>` ${t+1}. ${e.message} [${e.code}]`)).join("\n")),this.cause&&(e+=`\nCause: ${this.cause instanceof Error?this.cause.message:String(this.cause)}`),e}};function r(e,t){return new i({code:e,message:t})}function n(e,t){return new i({code:e,message:t})}var c={NOT_FOUND:"DB-001-NF",DUPLICATE_KEY:"DB-002-DUP",INVALID_COMMAND:"BUS-001",PERMISSION_DENIED:"AUTH-001-DENIED",BACKEND_ERROR:"SYS-002",INTERNAL_ERROR:"SYS-001",VALIDATION_FAILED:"VAL-001",CONCURRENCY_ERROR:"CON-001",RESOURCE_LOCKED:"DB-003-LOCK",OPERATION_ABORTED:"BUS-002-ABORT"},d={notFound:(e,t)=>new i({code:c.NOT_FOUND,message:t,path:e}),duplicateKey:(e,t)=>new i({code:c.DUPLICATE_KEY,message:t,path:e}),permissionDenied:(e,t)=>new i({code:c.PERMISSION_DENIED,message:t,operation:e}),validationFailed:(e,t)=>new i({code:c.VALIDATION_FAILED,issues:e,path:t}),internalError:(e,t)=>new i({code:c.INTERNAL_ERROR,message:t,cause:e})},h={ok:e=>({ok:!0,value:e}),fail:e=>({ok:!1,error:e})};export{c as CommonErrors,e as ErrorCodes,d as Errors,h as Result,i as SystemError,r as createError,n as error,a as getErrorMetadata,o as isKnownErrorCode,s as registerErrorCode};
1
+ var e={VALIDATION_FAILED:{code:"VAL-001",name:"VALIDATION_FAILED",description:"Input validation failed due to one or more invalid fields",category:"validation",httpStatus:400,logLevel:"warn"},REQUIRED_FIELD_MISSING:{code:"VAL-002",name:"REQUIRED_FIELD_MISSING",description:"A required field was not provided in the request",category:"validation",httpStatus:400,logLevel:"warn"},INVALID_FORMAT:{code:"VAL-003",name:"INVALID_FORMAT",description:"Field value does not match expected format",category:"validation",httpStatus:400,logLevel:"warn"},NOT_FOUND:{code:"DB-001-NF",name:"NOT_FOUND",description:"The requested resource could not be found",category:"database",httpStatus:404,logLevel:"info",action:"Verify the resource identifier exists before accessing"},DUPLICATE_KEY:{code:"DB-002-DUP",name:"DUPLICATE_KEY",description:"A unique constraint violation occurred",category:"database",httpStatus:409,logLevel:"warn",action:"Check if the resource already exists before creation"},RESOURCE_LOCKED:{code:"DB-003-LOCK",name:"RESOURCE_LOCKED",description:"The resource is currently locked by another operation",category:"database",httpStatus:409,logLevel:"warn",action:"Retry the operation after a brief delay"},PERMISSION_DENIED:{code:"AUTH-001-DENIED",name:"PERMISSION_DENIED",description:"The authenticated user lacks permission for this operation",category:"auth",httpStatus:403,logLevel:"warn",action:"Check user roles and permissions"},UNAUTHENTICATED:{code:"AUTH-002-UNAUTH",name:"UNAUTHENTICATED",description:"Authentication is required for this operation",category:"auth",httpStatus:401,logLevel:"info",action:"Provide valid authentication credentials"},INVALID_COMMAND:{code:"BUS-001",name:"INVALID_COMMAND",description:"The command or operation is invalid for the current state",category:"business",httpStatus:400,logLevel:"warn"},OPERATION_ABORTED:{code:"BUS-002-ABORT",name:"OPERATION_ABORTED",description:"The operation was explicitly aborted",category:"business",httpStatus:409,logLevel:"info"},INTERNAL_ERROR:{code:"SYS-001",name:"INTERNAL_ERROR",description:"An unexpected internal error occurred",category:"system",httpStatus:500,logLevel:"error",action:"Check system logs for stack traces and diagnostic information"},BACKEND_ERROR:{code:"SYS-002",name:"BACKEND_ERROR",description:"An error occurred in a backend service",category:"system",httpStatus:502,logLevel:"error"},CONCURRENCY_ERROR:{code:"CON-001",name:"CONCURRENCY_ERROR",description:"A concurrency conflict occurred during the operation",category:"concurrency",httpStatus:409,logLevel:"warn",action:"Retry the operation with updated data"}},t=new Map;function s(s){if(Object.values(e).find(e=>e.code===s.code))throw new Error(`Cannot register custom error code "${s.code}": already exists as built-in error`);if(t.has(s.code))throw new Error(`Custom error code "${s.code}" is already registered`);t.set(s.code,s)}function a(s){const a=Object.values(e).find(e=>e.code===s);if(a)return a;const o=t.get(s);return o||{code:s,name:s.replace(/-/g,"_"),description:`Unknown error: ${s}`,category:"custom",httpStatus:500,logLevel:"error",action:"Check if this error code is properly registered or handle as unknown error"}}function o(s){return Object.values(e).some(e=>e.code===s)||t.has(s)}var r=class e extends Error{code;codeMetadata;severity;path;operation;issues;cause;constructor(t){const s={...a(t.code),...t.metadata,code:t.code};super(t.message??s.description),this.name="SystemError",this.code=t.code,this.codeMetadata=s,this.severity=t.severity??"error",this.path=t.path,this.operation=t.operation,this.issues=t.issues??[],this.cause=t.cause,Object.setPrototypeOf(this,e.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,e)}withPath(t){return new e({code:this.code,message:this.message,severity:this.severity,path:t,operation:this.operation,issues:this.issues,cause:this.cause,metadata:this.codeMetadata})}withOperation(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:t,issues:this.issues,cause:this.cause,metadata:this.codeMetadata})}withIssue(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,issues:[...this.issues,t],cause:this.cause,metadata:this.codeMetadata})}withIssues(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,issues:[...this.issues,...t],cause:this.cause,metadata:this.codeMetadata})}withCause(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,issues:this.issues,cause:t,metadata:this.codeMetadata})}getHttpStatus(){return this.codeMetadata.httpStatus}extractChronologicalChain(e){if(!e)return[];if(Array.isArray(e))return e.flatMap(e=>this.extractChronologicalChain(e));if(e instanceof AggregateError)return e.errors.flatMap(e=>this.extractChronologicalChain(e));let t={name:e instanceof Error?e.name:"UnknownError",message:e instanceof Error?e.message:"object"==typeof e&&null!==e?JSON.stringify(e):String(e),code:e?.code,operation:e?.operation};if(!(e instanceof Error)&&"object"==typeof e&&null!==e){const t=Object.keys(e);if(1===t.length&&"object"==typeof e[t[0]])return this.extractChronologicalChain(e[t[0]])}const s=e?.cause;return s?[...this.extractChronologicalChain(s),t]:[t]}toLogEntry(){const e=this.extractChronologicalChain(this.cause);e.push({name:this.name,message:this.message,code:this.code,operation:this.operation});const t=e.map(e=>`${e.operation||e.code||e.name} (${e.message})`).join(" --\x3e ");return{name:this.name,code:this.code,category:this.codeMetadata.category,severity:this.severity,message:`${this.message} | Failure Path: ${t}`,operation:this.operation,path:this.path,issues:this.issues,history:e,stack:this.stack,timestamp:(new Date).toISOString()}}serializeCause(e){return e?Array.isArray(e)?e.map(e=>this.serializeCause(e)):e instanceof AggregateError?{name:e.name,message:e.message,errors:e.errors.map(e=>this.serializeCause(e)),stack:e.stack}:e instanceof Error?"function"==typeof e.toJSON?e.toJSON():{name:e.name,message:e.message,stack:e.stack}:e:e}toJSON(){return{name:this.name,code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,codeMetadata:this.codeMetadata,issues:this.issues,cause:this.serializeCause(this.cause)}}toString(){let e=`[${this.code}] ${this.message} (${this.codeMetadata.category})`;return this.path&&(e+=` at '${this.path}'`),this.operation&&(e+=` during '${this.operation}'`),this.issues.length>0&&(e+="\nIssues:\n"+this.issues.map((e,t)=>` ${t+1}. ${e.message} [${e.code}]`).join("\n")),this.cause&&(e+=`\nCause: ${this.cause instanceof Error?this.cause.message:String(this.cause)}`),e}};function i(e,t){return new r({code:e,message:t})}function n(e,t){return new r({code:e,message:t})}var c={NOT_FOUND:"DB-001-NF",DUPLICATE_KEY:"DB-002-DUP",INVALID_COMMAND:"BUS-001",PERMISSION_DENIED:"AUTH-001-DENIED",BACKEND_ERROR:"SYS-002",INTERNAL_ERROR:"SYS-001",VALIDATION_FAILED:"VAL-001",CONCURRENCY_ERROR:"CON-001",RESOURCE_LOCKED:"DB-003-LOCK",OPERATION_ABORTED:"BUS-002-ABORT"},h={notFound:(e,t)=>new r({code:c.NOT_FOUND,message:t,path:e}),duplicateKey:(e,t)=>new r({code:c.DUPLICATE_KEY,message:t,path:e}),permissionDenied:(e,t)=>new r({code:c.PERMISSION_DENIED,message:t,operation:e}),validationFailed:(e,t)=>new r({code:c.VALIDATION_FAILED,issues:e,path:t}),internalError:(e,t)=>new r({code:c.INTERNAL_ERROR,message:t,cause:e})},d={ok:e=>({ok:!0,value:e}),fail:e=>({ok:!1,error:e})};export{c as CommonErrors,e as ErrorCodes,h as Errors,d as Result,r as SystemError,i as createError,n as error,a as getErrorMetadata,o as isKnownErrorCode,s as registerErrorCode};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asaidimu/utils-error",
3
- "version": "1.0.0",
3
+ "version": "1.1.1",
4
4
  "description": "A collection of error utilities.",
5
5
  "main": "index.js",
6
6
  "module": "index.mjs",