refactor: DRY improvements and type-safe error handling
DRY Improvements (api.ts): - Extract requireApiKey() helper for API authentication - Extract getCorsHeaders() helper for CORS header generation - Eliminate ~20 lines of duplicated code Type Safety (new utils/error.ts): - Add toError() utility for safe error type conversion - Replace all 6 `error as Error` assertions with toError() - Proper handling of Error, string, and unknown types Error Handling (api.ts): - Add explicit JSON parsing error handling to all POST endpoints - Return 400 Bad Request for malformed JSON - Clearer error messages for API consumers Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
52
src/utils/error.ts
Normal file
52
src/utils/error.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* Error handling utilities for type-safe error conversion
|
||||
*
|
||||
* @module error
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { toError } from './utils/error';
|
||||
*
|
||||
* try {
|
||||
* // ...
|
||||
* } catch (error) {
|
||||
* logger.error('Operation failed', toError(error));
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
|
||||
/**
|
||||
* unknown 타입을 Error로 안전하게 변환
|
||||
*
|
||||
* catch 블록에서 unknown 타입의 error를 Error 객체로 변환합니다.
|
||||
* TypeScript strict mode에서 `error as Error` 타입 단언을 피하기 위해 사용합니다.
|
||||
*
|
||||
* @param error - catch 블록에서 받은 unknown 타입 에러
|
||||
* @returns Error 객체
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* try {
|
||||
* await riskyOperation();
|
||||
* } catch (error) {
|
||||
* // ✅ Type-safe
|
||||
* logger.error('Operation failed', toError(error));
|
||||
*
|
||||
* // ❌ Type assertion (avoid)
|
||||
* // logger.error('Operation failed', error as Error);
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
export function toError(error: unknown): Error {
|
||||
// Already an Error object - return as-is
|
||||
if (error instanceof Error) {
|
||||
return error;
|
||||
}
|
||||
|
||||
// String error - wrap in Error object
|
||||
if (typeof error === 'string') {
|
||||
return new Error(error);
|
||||
}
|
||||
|
||||
// Other types - convert to string and wrap
|
||||
return new Error(String(error));
|
||||
}
|
||||
Reference in New Issue
Block a user