80 lines
2.1 KiB
TypeScript
80 lines
2.1 KiB
TypeScript
/**
|
|
* An error returned by a GraphQL server.
|
|
*/
|
|
export interface GraphError {
|
|
message: string;
|
|
path?: string[];
|
|
}
|
|
|
|
/** RawError is an error that can be converted to a string by ErrorMessage */
|
|
export type RawError = Error | string | GraphError[];
|
|
|
|
export class ErrorMessage {
|
|
private _lines: string[] = [];
|
|
|
|
/**
|
|
* Converts a RawError to an array of lines and stores it for later access,
|
|
* or initializes without any errors if the input is null or undefined.
|
|
* @param raw The raw error to convert and store, or null/undefined for no error.
|
|
* @throws If the raw error is of an unsupported type.
|
|
*/
|
|
constructor(raw: RawError | null | undefined) {
|
|
if (raw) {
|
|
this._lines = ErrorMessage.rawErrorToLines(raw);
|
|
}
|
|
}
|
|
|
|
/** returns the stored lines */
|
|
get lines(): string[] {
|
|
return this._lines;
|
|
}
|
|
/** returns the error lines as a string, separated by newlines */
|
|
toString(): string {
|
|
return this._lines.join('\n');
|
|
}
|
|
/** returns the error lines as an HTML string, separated by <br /> */
|
|
toHTML(): string {
|
|
return this._lines.join('<br />');
|
|
}
|
|
|
|
/** returns true if there are any error lines */
|
|
hasError(): boolean {
|
|
return this._lines.length > 0;
|
|
}
|
|
|
|
/** adds a new line to the error message */
|
|
addLine(line: string): void {
|
|
this._lines.push(line);
|
|
}
|
|
|
|
/** optionally returns a new ErrorMessage only if the RawError is not empty */
|
|
static from(raw: RawError | null | undefined): ErrorMessage | null {
|
|
if (!raw) return null;
|
|
return new ErrorMessage(raw);
|
|
}
|
|
|
|
/** converts a RawError to an array of lines */
|
|
static rawErrorToLines(raw: RawError | null | undefined): string[] {
|
|
if (!raw) return ['No error'];
|
|
|
|
let errorLines: string[];
|
|
if (typeof raw === 'string') {
|
|
errorLines = [raw];
|
|
} else if (raw instanceof Error) {
|
|
errorLines = [raw.message];
|
|
} else if (Array.isArray(raw)) {
|
|
errorLines = raw.map((e) => {
|
|
const messageString = e.message || 'Unknown error';
|
|
if (e.path && e.path.length > 0) {
|
|
return `"${messageString}" at ${e.path.join('.')}`;
|
|
}
|
|
return messageString;
|
|
});
|
|
} else {
|
|
throw `Bad error value ${raw}`;
|
|
}
|
|
|
|
return errorLines;
|
|
}
|
|
}
|