Spring Boot 애플리케이션에서는 예외 메시지를 코드에서 직접 하드코딩하는 대신, 프로퍼티 파일을 활용하여 중앙에서 관리할 수 있다.
우선, messages.properties
파일을 src/main/resources
경로에 생성하고 예외 메시지를 정의
이제 특정 예외가 발생할 때, 해당 키를 사용하여 메시지를 불러올 수 있도록 설정
CommonException
클래스 만들기모든 예외의 부모 클래스 역할을 하는 CommonException
을 생성
NotFoundException
클래스 구현프로퍼티에서 예외 메시지를 가져오는 NotFoundException
클래스를 작성.
이제 NotFoundException
을 생성할 때, 프로퍼티에서 해당 키의 메시지를 가져와 예외 메시지로 설정
예외를 발생시킬 때 프로퍼티 키를 전달하여 적절한 메시지를 반환 가능
throw new NotFoundException("NotFound.board");
위 코드를 실행하면 messages.properties
에서 NotFound.board
키를 찾아 "게시판을 찾을 수 없습니다." 라는 메시지를 반환
Spring Boot의 MessageSource
를 활용하면 다국어 지원도 가능.
예를 들어 messages_en.properties
파일을 추가하여 영어 메시지를 설정 가능
# messages_en.properties
NotFound.board=Board not found.
NotFound.boardData=Post not found.
NotFound.comment=Comment not found.
RequiredCheck.guestPw=Password confirmation is required.
Mismatch.password=Passwords do not match.
그리고 application.yml
또는 application.properties
에서 기본 메시지 소스를 등록.
spring:
messages:
basename: messages
encoding: UTF-8
이제 클라이언트의 요청 언어(Accept-Language
헤더)에 따라 한국어 또는 영어 메시지가 자동으로 적용된다.
위와 같이 프로퍼티 파일을 활용하면 예외 메시지를 한 곳에서 효율적으로 관리할 수 있으며, 다국어 지원까지 가능해지고, 이를 통해 코드의 유지보수성을 높이고, 보다 깔끔한 예외 처리 방식을 구현할 수 있다.