- Use better error messages with more context. - Unify their validation logic and share tests. - Validate also type of the name. - Refactor node (Script/Category) parser tests for easier future changes and cleaner test code (using `TestBuilder` to do dirty work in unified way). - Add more tests. Custom `Error` properties are compared manually due to `chai` not supporting deep equality checks (chaijs/chai#1065, chaijs/chai#1405).
36 lines
1.1 KiB
TypeScript
36 lines
1.1 KiB
TypeScript
import { NodeType } from './NodeType';
|
|
import { NodeData } from './NodeData';
|
|
|
|
export class NodeDataError extends Error {
|
|
constructor(message: string, public readonly context: INodeDataErrorContext) {
|
|
super(createMessage(message, context));
|
|
Object.setPrototypeOf(this, new.target.prototype); // https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget
|
|
this.name = new.target.name;
|
|
}
|
|
}
|
|
|
|
export interface INodeDataErrorContext {
|
|
readonly type?: NodeType;
|
|
readonly selfNode: NodeData;
|
|
readonly parentNode?: NodeData;
|
|
}
|
|
|
|
function createMessage(errorMessage: string, context: INodeDataErrorContext) {
|
|
let message = '';
|
|
if (context.type !== undefined) {
|
|
message += `${NodeType[context.type]}: `;
|
|
}
|
|
message += errorMessage;
|
|
message += `\n${dump(context)}`;
|
|
return message;
|
|
}
|
|
|
|
function dump(context: INodeDataErrorContext): string {
|
|
const printJson = (obj: unknown) => JSON.stringify(obj, undefined, 2);
|
|
let output = `Self: ${printJson(context.selfNode)}`;
|
|
if (context.parentNode) {
|
|
output += `\nParent: ${printJson(context.parentNode)}`;
|
|
}
|
|
return output;
|
|
}
|