diff --git a/src/lib/error.ts b/src/lib/error.ts new file mode 100644 index 0000000..b5a950e --- /dev/null +++ b/src/lib/error.ts @@ -0,0 +1,59 @@ +/** + * 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; + } +} diff --git a/src/lib/index.ts b/src/lib/index.ts index 81eebe7..e743446 100644 --- a/src/lib/index.ts +++ b/src/lib/index.ts @@ -38,3 +38,4 @@ export { ToolbarGroup, Toolbar } from './Toolbar'; +export { type GraphError, type RawError, ErrorMessage } from './error';