티스토리 뷰

Skill/spring

spring] 에러 메시지 반환

진열사랑 2025. 5. 29. 20:37

현재 작성하신 Java Spring Controller에서는 Exception을 발생시키긴 하지만, 실제로 클라이언트에게 그 메시지를 전달하고 있지 않기 때문에 클라이언트는 단순히 정상 응답을 받거나, 경우에 따라 에러 내용 없이 실패할 수 있습니다.

클라이언트에게 **"해석 실패되었습니다."**라는 메시지를 전달하려면, 다음 중 하나의 방법을 적용하시는 것이 좋습니다.


✅ 권장 방법: @ControllerAdvice + @ExceptionHandler를 통한 전역 예외 처리

  1. 커스텀 예외 클래스 정의
public class AnalysisFailedException extends RuntimeException {
    public AnalysisFailedException(String message) {
        super(message);
    }
}
  1. Controller에서 커스텀 예외 던지기
@PostMapping
public InftwtAnlsResponseDto postInftwtAnlss(@RequestBody InftwtAnlsSaveDto inftwtAnlsSaveDto) {
    InftwtAnlsResponseDto result;

    try {
        result = inftwtAnlsService.save(inftwtAnlsSaveDto);

        FlaskServerResponse res = flaskServer.callInfiltration(result.getInftwtAnlsSn());
        if (!"0000".equals(res.getResultCode())) {
            throw new AnalysisFailedException("해석 실패되었습니다.");
        }

    } catch (Exception e) {
        // 로그는 찍고, 예외를 다시 던집니다.
        e.printStackTrace();
        throw e;
    }

    return result;
}
  1. 전역 예외 처리 클래스 작성
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(AnalysisFailedException.class)
    public ResponseEntity<Map<String, String>> handleAnalysisFailedException(AnalysisFailedException ex) {
        Map<String, String> errorResponse = new HashMap<>();
        errorResponse.put("error", ex.getMessage());
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse);
    }

    // 기타 예외도 필요 시 여기에 추가
}

🔍 클라이언트 응답 예시 (JSON)

HTTP 400 Bad Request
{
  "error": "해석 실패되었습니다."
}

⚠️ 기존 코드의 문제점

현재 코드에서는 Exception을 catch하고 e.printStackTrace();만 하면서 응답은 여전히 정상적인 result 객체를 리턴하고 있습니다. 이렇게 하면 클라이언트는 실패 여부를 알 수 없습니다.


📌 참고 사항

  • throws Exception을 Controller 메서드에 사용하는 것은 지양하는 것이 좋습니다. 대신, 예외를 컨트롤해서 처리하거나 RuntimeException 계열을 사용하세요.
  • 클라이언트에서 JSON으로 에러 메시지를 받기 위해서는 @RestControllerAdvice를 활용한 예외 처리가 가장 표준적이고 권장되는 방식입니다.

'Skill > spring' 카테고리의 다른 글

Spring Webflux  (0) 2025.06.10
FeignClient -feign.RetryableException  (0) 2025.06.10
spring cloud 설정  (0) 2025.05.29
JPA] 설정  (0) 2025.05.29
spring boot] CORS 설정  (0) 2025.05.29
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함