SoException은 Sonamu의 모든 예외 클래스가 상속하는 추상 기본 클래스입니다. HTTP 상태 코드와 메시지, 추가 페이로드를 포함할 수 있습니다.
타입 정의
abstract class SoException extends Error { constructor( public readonly statusCode: number, public message: LocalizedString, public payload?: unknown, );}
속성
statusCode
readonly statusCode: number
HTTP 응답 상태 코드입니다. 예외가 발생하면 Fastify가 이 코드로 응답합니다.
message
message: LocalizedString;
예외 메시지입니다. LocalizedString 타입으로, Sonamu의 다국어 지원 시스템을 통해 지역화된 문자열을 전달합니다.
payload
payload?: unknown
선택적 추가 데이터입니다. 예외와 관련된 상세 정보를 전달할 때 사용합니다.사용 예시:
throw new BadRequestException("유효하지 않은 이메일 형식입니다", { field: "email", providedValue: "invalid-email", expectedFormat: "user@example.com",});
유틸리티 함수
isSoException()
주어진 값이 SoException 인스턴스인지 확인합니다.
function isSoException(err: unknown): err is SoException;
사용 예시:
try { // 어떤 작업} catch (err) { if (isSoException(err)) { console.log(`Status: ${err.statusCode}`); console.log(`Message: ${err.message}`); console.log(`Payload:`, err.payload); } else { // 다른 타입의 에러 처리 }}
내장 예외 클래스
Sonamu는 일반적인 HTTP 오류 상황을 위한 여러 내장 예외 클래스를 제공합니다.
BadRequestException (400)
잘못된 매개변수 등 요청사항에 문제가 있는 경우 사용합니다.
class BadRequestException extends SoException
사용 예시:
@api()async createUser(email: string, password: string) { if (!email.includes("@")) { throw new BadRequestException("유효하지 않은 이메일 형식입니다"); } if (password.length < 8) { throw new BadRequestException("비밀번호는 최소 8자 이상이어야 합니다", { minLength: 8, providedLength: password.length }); } // 사용자 생성 로직}
UnauthorizedException (401)
로그인이 필요한 경우 로그아웃 상태이거나 접근 권한이 없는 요청 시 사용합니다.
class UnauthorizedException extends SoException
사용 예시:
@api()async getMyProfile(ctx: Context) { if (!ctx.user) { throw new UnauthorizedException("로그인이 필요합니다"); } return this.findById("A", ctx.user.id);}
NotFoundException (404)
존재하지 않는 레코드에 접근 시 사용합니다.
class NotFoundException extends SoException
사용 예시:
@api()async getUserById(id: number) { const user = await this.findOne("A", { id }); if (!user) { throw new NotFoundException(`사용자를 찾을 수 없습니다 (ID: ${id})`); } return user;}
InternalServerErrorException (500)
내부 처리 로직(외부 API 호출 포함) 오류 발생 시 사용합니다.
class InternalServerErrorException extends SoException
사용 예시:
@api()async processPayment(orderId: number) { try { const result = await externalPaymentAPI.charge(orderId); return result; } catch (err) { throw new InternalServerErrorException( "결제 처리 중 오류가 발생했습니다", { orderId, originalError: err } ); }}
ServiceUnavailableException (503)
현재 상태에서 처리가 불가능한 경우 사용합니다.
class ServiceUnavailableException extends SoException
사용 예시:
@api()async getRecommendations() { if (!this.mlServiceAvailable) { throw new ServiceUnavailableException( "추천 서비스가 일시적으로 사용 불가능합니다" ); } return this.fetchRecommendations();}