add error helper

This commit is contained in:
Elijah Duffy
2025-07-16 17:29:07 -07:00
parent 8d12c1b05d
commit f55943d474
2 changed files with 60 additions and 0 deletions

59
src/lib/error.ts Normal file
View File

@@ -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('<br />');
} else {
throw `Bad error value ${raw}`;
}
return errorString;
}
}

View File

@@ -38,3 +38,4 @@ export {
ToolbarGroup,
Toolbar
} from './Toolbar';
export { type GraphError, type RawError, ErrorMessage } from './error';