diff --git a/lib/CustomError.ts b/lib/CustomError.ts index 9834f31..9bc282f 100644 --- a/lib/CustomError.ts +++ b/lib/CustomError.ts @@ -23,4 +23,35 @@ export default class CustomError extends Error { this.stack = new Error(message).stack; } } + + toJSON() { + const jsonStructure: { + message: string; + statusCode: number; + errorCode: number; + name: string; + stack?: string; + originalError?: { + message: string; + name: string; + stack?: string; + }; + } = { + message: this.message, + statusCode: this.statusCode, + errorCode: this.errorCode, + name: this.name, + stack: this.stack, + }; + + if (this.originalError) { + jsonStructure.originalError = { + name: this.originalError.name, + message: this.originalError.message, + stack: this.originalError.stack, + }; + } + + return jsonStructure; + } } diff --git a/tests/CustomError.spec.ts b/tests/CustomError.spec.ts index d0a9223..ce764fd 100644 --- a/tests/CustomError.spec.ts +++ b/tests/CustomError.spec.ts @@ -38,6 +38,12 @@ try { // The response error code should have been set assert.strictEqual(err.statusCode, 400); - // The customer error code should have been set + // Serializes JSON structure assert.strictEqual(err.errorCode, 4000); + assert.strictEqual(err.toJSON().message, "It went bad!"); + assert.strictEqual(err.toJSON().statusCode, 400); + assert.strictEqual(err.toJSON().errorCode, 4000); + assert.strictEqual(err.toJSON().name, "CustomError"); + assert.notStrictEqual(err.toJSON().originalError, undefined); + assert.notStrictEqual(err.toJSON().stack, undefined); }