
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/account")
public class AccountApiController {
@GetMapping("/me")
public ApiResponse<AccountMeResponse> me() {
AccountMeResponse data = AccountMeResponse.builder()
.name("홍길동")
.email("sad@gmail.com")
.registeredAt(LocalDateTime.now())
.build();
try {
String str = "안녕하세요";
int i = Integer.parseInt(str);
} catch (Exception e) {
throw new IllegalStateException("사용자 me 호출시 에러 발생!");
}
return ApiResponse.OK(data);
}
}
@Slf4j
@RestControllerAdvice
@Order(value = Integer.MIN_VALUE)
public class ApiExceptionHandler {
@ExceptionHandler(value = IllegalStateException.class)
public ResponseEntity<ApiResponse<Object>> apiException(ApiException apiException) {
log.error("", apiException);
ErrorCodeIfs errorCode = apiException.getErrorCodeIfs();
return ResponseEntity
.status(errorCode.getHttpStatusCode())
.body(ApiResponse.ERROR(errorCode, apiException.getErrorDescription()));
}
}
@RestControllerAdvice 어노테이션을 사용하여 예외 처리에 대한 객체를 생성하여 리턴할 수 있도록 함@ControllerAdvice 어노테이션으로 사용@ExceptionHandler 어노테이션을 사용하여 어떠한 예외 클래스에 대해서 처리할지 명시!! 예기치 못한 에러나 상황에 대한 로직 처리를 위해 예외 처리는 반드시 중요하다는 것을 명심해야 함
소중한 정보 감사드립니다!