[스프링부트] 23. Blog v2 : Exception

문정준's avatar
Apr 10, 2025
[스프링부트] 23. Blog v2 : Exception
✏️

예외 처리

  • 기존 에러 처리는 RuntimeException으로 한 번에 처리했기 때문에, 케이스별 분류가 불가
  • 직접 Exception 케이스를 만들어서, 유저가 발생시킬 수 있는 에러 별 분류가 필요
 

1. GlobalExceptionHandler

  • 유저의 오류는 40x 상태 코드를 반환
    • 400 : 잘못된 접근 (Bad Request)
    • 401 : 미인증 (Unauthorized)
    • 403 : 권한 없음 (Forbidden)
    • 404 : 자원 찾을 수 없음 (Not Found)
  • 500 : 예상치 못한 오류 (Unknown Server Error)
    • 지정한 오류 외의 모든 Exception을 캐치 후 log로 남김
 
  • GlobalExceptionHandler
    • 예외를 처리하는 클래스
    • 예외 코드에 따른 동작을 이 곳에서 설정
    • Exception40x : html 반환
    • ExceptionApi40x : JSON 반환
package shop.mtcoding.blog._core.error; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import shop.mtcoding.blog._core.error.ex.*; import shop.mtcoding.blog._core.util.Resp; import shop.mtcoding.blog._core.util.Script; @RestControllerAdvice // @ControllerAdvice : return view public class GlobalExceptionHandler { // 400 Bad Request @ExceptionHandler(Exception400.class) public String ex400(Exception400 e) { return Script.alert(e.getMessage()); } // 401 Unauthorized @ExceptionHandler(Exception401.class) public String ex401(Exception401 e) { return Script.alert(e.getMessage()); } // 403 Forbidden @ExceptionHandler(Exception403.class) public String ex403(Exception403 e) { return Script.back(e.getMessage()); } // 404 Not Found @ExceptionHandler(Exception404.class) public String ex404(Exception404 e) { return Script.back(e.getMessage()); } // Unknown Server Error @ExceptionHandler(Exception.class) public String exUnknown(Exception e) { return Script.back("관리자에게 문의해주세요."); } // 400 Bad Request @ExceptionHandler(ExceptionApi400.class) public Resp<?> exApi400(ExceptionApi400 e) { return Resp.fail(400, e.getMessage()); } // 401 Unauthorized @ExceptionHandler(ExceptionApi401.class) public Resp<?> exApi401(ExceptionApi401 e) { return Resp.fail(401, e.getMessage()); } // 403 Forbidden @ExceptionHandler(ExceptionApi403.class) public Resp<?> exApi403(ExceptionApi403 e) { return Resp.fail(403, e.getMessage()); } // 404 Not Found @ExceptionHandler(ExceptionApi404.class) public Resp<?> exApi404(ExceptionApi404 e) { return Resp.fail(404, e.getMessage()); } }
 

2. Exception

  • 각 에러마다 메시지를 반환하기 위해 RuntimeException을 extend
package shop.mtcoding.blog._core.error.ex; public class Exception400 extends RuntimeException { public Exception400(String message) { super(message); } }
package shop.mtcoding.blog._core.error.ex; public class ExceptionApi400 extends RuntimeException { public ExceptionApi400(String message) { super(message); } }
 
 

3. Script

  • 예외 상황 발생 시 클라이언트에게 알림을 보내거나, 페이지 이동, 뒤로 가기 등 특정한 행동을 하도록 함
package shop.mtcoding.blog._core.util; public class Script { public static String alert(String msg) { String html = """ <script> alert('${msg}'); </script> """.replace("${msg}", msg); return html; } public static String back(String msg) { String html = """ <script> alert('${msg}'); history.back(); </script> """.replace("${msg}", msg); return html; } public static String href(String msg, String location) { String html = """ <script> alert('${msg}'); location.href = '${location}'; </script> """.replace("${msg}", msg) .replace("${location}", location); return html; } }
Share article

sxias