
| 상태 코드 | 설명 | |
| 400 | BAD_REQUST | 일반적인 요청 실패 |
| 401 | UNAUTHORIZED | 클라이언트 인증 문제 |
| 403 | FORBIDDEN | 인증 상태와 상관없이 접근 금지 |
| 404 | NOT_FOUND | 요청 url에 해당하는 리소스 없음 |
| 405 | METHOD_NOT_ALLOWD | http 메서드가 지원되지 않음 |
| 406 | NOT_ACCEPTABLE | 요청된 리소스 미디어 타입을 제공x |
| 409 | CONFILCT | 리소스 상태에 위반되는 행위 |
| 412 | PRECONDITION_FAILD | 조건부 연산을 지원 |
| 415 | UNSUPPORTED_MEDIA_TYPE | 요청 페이로드에 있는 미디어 타입 처리x |
| 500 | INTERNAL_SERVER_ERROR | api가 잘못 작동 |
// 메서드에 선언
@Controller
public class Example01Controller {
@ResponseStatus(value=HttpStatus.BAD_REQUEST, reason="요청 실패했습니다.")
@GetMapping("/exam01")
public void requestMethod() {
System.out.print(new IllegalArgumentException("요청 실패했습니다.").getMessage());
}
}
// 클래스에 선언
@Controller
public class Example02Controller {
@GetMapping("/exam02")
public void requestMethod() throws Exception {
throw new Exception(new UserException("UserException 메시지입니다"));
}
}
@Controller
public class Example03Controller {
@GetMapping("/exam03")
public void requestMethod(){
throw new UserException("UserException 메시지입니다");
}
@ExceptionHandler(UserException.class) // 예외 클래스 UserException
public String handleException(UserException ex, Model model) {
model.addAttribute("data1", ex.getMessage());
model.addAttribute("data2", ex);
return "viewPage01";
}
}
<html>
<head>
<title>Chap11</title>
</head>
<body>
<h3>예외 처리</h3>
<p>오류 메시지: [[${data1}]] //
<p>예외 발생: [[${data2}]]
</body>
</html>
@Controller
public class Example04Controller {
@GetMapping("/exam04")
public void requestMethod(){
throw new UserException("UserException 메시지입니다");
}
}
@ControllerAdvice(basePackages={"com.springboot"}) // 여러 컨트롤러에서 발생한 예외
public class GlobalException{
@ExceptionHandler(value={RuntimeException.class})
private String handleErrorMethod(Exception ex, Model model) {
model.addAttribute("data1", "GlobalException 메시지입니다");
model.addAttribute("data2", ex );
return "viewPage01";
}
}


@Controller
public class Example01Controller {
@GetMapping("/exam01")
public String requestMethod2(Model model) {
Logger logger = LoggerFactory.getLogger(Example01Controller.class);
logger.trace("Trace 메시지!");
logger.debug("Debug 메시지!");
logger.info("Info 메시지!"); // INFO 레벨 이상
logger.warn("Warn 메시지!");
logger.error("Error 메시지!");
model.addAttribute("data","Slf4j로 로그 출력하기" );
return "viewPage";
}
}
<html>
<head>
<title>Chap12</title>
</head>
<body>
<h3>로그 기록</h3>
<p> [[${data}]]
</body>
</html>
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Controller
public class Example02Controller {
@GetMapping("/exam02")
public String requestMethod2(Model model) {
// 로그 객체 선언 불필요
log.trace("Trace 메시지!");
log.debug("Debug 메시지!");
log.info("Info 메시지!"); // INFO 레벨 이상
log.warn("Warn 메시지!");
log.error("Error 메시지!");
model.addAttribute("data","@Slf4j로 로그 출력하기" );
return "viewPage";
}
}
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<Console name="console" target="SYSTEM_OUT">
<PatternLayout pattern="%d %5p [%C] %m%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="info" additivity="true">
<AppenderRef ref="console"/>
</Root>
</Loggers>
</Configuration>
@Slf4j
public class ExampleInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
log.info("preHandle() 호출......");
if (handler instanceof HandlerMethod) {
HandlerMethod method = (HandlerMethod) handler;
log.info("핸들러 메소드명 : " + method.getMethod().getName());
}
return HandlerInterceptor.super.preHandle(request, response, handler);
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
log.info("postHandle() 호출......");
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
log.info("afterCompletion() 호출......");
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
출처: 송미영,『 스프링 부트 완전 정복 : 개념부터 실전 프로젝트까지 』, 길벗(2024).
Coner Spring1
Editor: soyee
| [Spring 1팀] 14장. 데이터베이스 연동 (0) | 2026.01.13 |
|---|---|
| [Spring 1팀] 13. RESTful 웹 서비스 (0) | 2026.01.02 |
| [Spring 1팀] 10장. 시큐리티 처리 (0) | 2025.12.19 |
| [Spring 1팀] 9장. 유효성 처리 (0) | 2025.11.28 |
| [Spring 1팀] 8장. 다국어 처리 (0) | 2025.11.21 |