Spring Boot | 예외 처리 | 특정 예외가 발생했을 때의 상태 코드 지정하기
코드 작성
src/main/java/sample/springboot/web/MyException.java
package sample.springboot.web;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class MyException extends RuntimeException {
private static final long serialVersionUID = 1L;
public MyException(String msg) {
super(msg);
}
}
src/main/java/sample/springboot/web/WebApiController.java
package sample.springboot.web;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class WebApiController {
@RequestMapping(method=RequestMethod.GET)
public void method1() {
throw new MyException("test exception");
}
}
실행 결과
curl으로 테스트하기
$ curl http://localhost:8080/api
{"timestamp":1430489386562,"status":400,"error":"Bad Request","exception":"sample.springboot.web.MyException","message":"test exception","path":"/api"}
설명
- 작성한 예외 클래스를 @ResponseStatus에 어노테이션을 부여함으로써, 그 예외가 throw되었을 때의 상태 코드를 지정할 수 있다.
- 브라우저에서 액세스하는 경우 기본 오류 페이지가 표시된다.