PYTHON · 예외처리
커스텀 예외 계층
프로젝트별 예외 계층을 설계하여 체계적인 에러 처리를 구현합니다.
예외처리중급custom exception예외 계층AppError에러
핵심 설명
프로젝트별 예외 계층을 설계하여 체계적인 에러 처리를 구현합니다.
Python code
class AppError(Exception):
"""애플리케이션 기본 예외"""
def __init__(self, message: str, code: str = "UNKNOWN"):
super().__init__(message)
self.code = code
class ValidationError(AppError):
def __init__(self, field: str, message: str):
super().__init__(f"{field}: {message}", code="VALIDATION")
self.field = field
class NotFoundError(AppError):
def __init__(self, resource: str, resource_id):
super().__init__(
f"{resource}({resource_id})을 찾을 수 없음",
code="NOT_FOUND"
)
self.resource = resource
self.resource_id = resource_id
class AuthError(AppError):
def __init__(self, message="인증 실패"):
super().__init__(message, code="AUTH")
# 사용 예시
def get_user(user_id: int):
if user_id <= 0:
raise ValidationError("user_id", "양수여야 합니다")
if user_id > 100:
raise NotFoundError("User", user_id)
return {"id": user_id}
# 계층적 에러 처리
for uid in [0, 200, 50]:
try:
print(get_user(uid))
except NotFoundError as e:
print(f"[{e.code}] {e.resource} 없음: {e.resource_id}")
except ValidationError as e:
print(f"[{e.code}] {e.field} 검증 실패")
except AppError as e:
print(f"[{e.code}] 앱 에러: {e}")학습 팁
예외에 code 필드를 추가하면 API 응답이나 로그에서 에러를 프로그래밍적으로 구분할 수 있습니다.
주의할 점
너무 세분화된 예외 계층은 관리가 어렵습니다. 3-4단계 이내로 유지하세요.
자주 묻는 질문
커스텀 예외 계층란 무엇인가요?
프로젝트별 예외 계층을 설계하여 체계적인 에러 처리를 구현합니다.
커스텀 예외 계층 학습 시 주의할 점은 무엇인가요?
너무 세분화된 예외 계층은 관리가 어렵습니다. 3-4단계 이내로 유지하세요.
Continue Learning
Python 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.