Skip to content

Commit

Permalink
Merge pull request #24 from kbariotis/serialize-json
Browse files Browse the repository at this point in the history
add JSON serialization
  • Loading branch information
kbariotis authored Dec 22, 2020
2 parents 0abba8b + 1199ed8 commit 09697cf
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
31 changes: 31 additions & 0 deletions lib/CustomError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
8 changes: 7 additions & 1 deletion tests/CustomError.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

0 comments on commit 09697cf

Please sign in to comment.