feat: add type-safe error handling utilities

- Add isError() type guard to check if value is Error instance
- Add getErrorMessage() utility for safe error message extraction
  in catch blocks (handles TypeScript 4.4+ unknown error type)
- Replace all (err as Error).message patterns with getErrorMessage(err)
  across server.ts, cli.ts, ralph-loop.ts, and screen-manager.ts
- Follows TypeScript best practice of treating caught errors as unknown

This improves code safety by properly handling the case where caught
values may not be Error instances (e.g., thrown strings or objects).

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
arkon
2026-01-21 14:07:04 +01:00
co-authored by Claude Opus 4.5
parent c33d6e0987
commit 384350f731
5 changed files with 74 additions and 32 deletions
+40
View File
@@ -615,3 +615,43 @@ export function createInitialState(): AppState {
config: { ...DEFAULT_CONFIG },
};
}
// ========== Error Handling Utilities ==========
/**
* Type guard to check if a value is an Error instance
* @param value The value to check
* @returns True if the value is an Error instance
*/
export function isError(value: unknown): value is Error {
return value instanceof Error;
}
/**
* Safely extracts an error message from an unknown caught value.
* Handles the TypeScript 4.4+ unknown error type in catch blocks.
*
* @param error The caught error (type unknown in strict mode)
* @returns A string error message
*
* @example
* ```typescript
* try {
* await riskyOperation();
* } catch (err) {
* console.error('Failed:', getErrorMessage(err));
* }
* ```
*/
export function getErrorMessage(error: unknown): string {
if (isError(error)) {
return error.message;
}
if (typeof error === 'string') {
return error;
}
if (error && typeof error === 'object' && 'message' in error) {
return String((error as { message: unknown }).message);
}
return 'An unknown error occurred';
}