Spring Boot | 예외 처리 | 컨트롤러 단위로 예외 처리를 정의하기
코드 작성
src/main/java/sample/springboot/web/WebApiController.java
package sample.springboot.web;
import org.springframework.web.bind.annotation.ExceptionHandler;
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");
}
@RequestMapping(value="/null", method=RequestMethod.GET)
public void method2() {
throw new NullPointerException("test exception");
}
@ExceptionHandler(NullPointerException.class)
public String handling(NullPointerException e) {
return "{\"message\":\"" + e.getMessage() + "\"}";
}
}
실행 결과
curl으로 테스트하기
$ curl http://localhost:8080/api/null
{"message":"test exception"}
설명
- @ExceptionHandler 어노테이션을 메소드에 정의하면, 해당 컨트롤러 내에서만 유효한 예외 핸들링이 가능하다.
- @ExceptionHandler의 value는 처리하고자 하는 예외(Exception) Class 객체를 건네 준다.