/**
* Structured error handling with sanitization
*/
export class SafeError extends Error {
constructor(
public code: string,
message: string,
public originalError?: unknown
) {
super(message);
this.name = 'SafeError';
}
toJSON() {
return {
error: this.message,
code: this.code,
...(process.env.NODE_ENV === 'development' && this.originalError
? { details: String(this.originalError) }
: {}),
};
}
}
/**
* Sanitize error message for user display
*/
export function sanitizeError(error: unknown): string {
if (error instanceof SafeError) {
return error.message;
}
if (error instanceof Error) {
// Hide sensitive details in production
if (process.env.NODE_ENV === 'production') {
return 'An error occurred during operation.';
}
return error.message;
}
return 'Unknown error occurred.';
}
/**
* Create a safe error response
*/
export function createErrorResponse(
code: string,
message: string,
originalError?: unknown
): { type: 'text'; text: string } {
const error = new SafeError(code, message, originalError);
return {
type: 'text',
text: JSON.stringify(error.toJSON()),
};
}
export const ErrorCodes = {
FILE_NOT_FOUND: 'FILE_NOT_FOUND',
ACCESS_DENIED: 'ACCESS_DENIED',
INVALID_INPUT: 'INVALID_INPUT',
COMMAND_FAILED: 'COMMAND_FAILED',
UNSUPPORTED_OPERATION: 'UNSUPPORTED_OPERATION',
INTERNAL_ERROR: 'INTERNAL_ERROR',
} as const;