/** * 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 _message: string; /** converts a RawError to a string and stores it for later access */ constructor(raw: RawError) { this._message = ErrorMessage.rawErrorToString(raw); } /** returns the stored message */ get message(): string { return this._message; } /** returns the error as a string */ toString(): string { return this._message; } /** 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 a string */ static rawErrorToString(raw: RawError | null | undefined): string { if (!raw) return 'No error'; let errorString: string; if (typeof raw === 'string') { errorString = raw; } else if (raw instanceof Error) { errorString = raw.message; } else if (Array.isArray(raw)) { errorString = raw .flatMap((e) => { const messageString = e.message || 'Unknown error'; if (e.path && e.path.length > 0) { return `"${messageString}" at ${e.path.join('.')}`; } }) .join('
'); } else { throw `Bad error value ${raw}`; } return errorString; } }