Spring Framework
[Spring] Exception 처리
헤르메스의날개
2021. 6. 8. 22:08
728x90
@ExceptionHandler 를 사용하면, Exception 을 Catch 할 수 있습니다.
@ExceptionHandler는 Controller 에서만 사용 가능합니다.
package test.controller;
import java.util.ArrayList;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class TestController {
@GetMapping("/test1")
public String test1(Model model) {
ArrayList<String> list = null;
list.add("문자열");
return "test1";
}
@ExceptionHandler(ArrayIndexOutOfBoundsException.class)
public String exception1() {
return "error1";
}
}
Global Exception Handler는 모든 Controller에서 발생하는 예외를 처리할 수 있습니다.
package test.exception;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler extends RuntimeException{
@ExceptionHandler(java.lang.NullPointerException.class)
public String handleException() {
return "error2";
}
}
@ExceptionHandler 와 @ControllerAdvice 의 우선순위
Controller 안의 @ExceptionHandler 가 먼저 처리됩니다.
그 다음에 @ControllerAdvice의 @ExceptionHandler 가 처리됩니다. ( 번외로 그 다음은 web.xml 에 정의된 error-page 가 호출됩니다. )
같은 @ControllerAdvice의 우선순위는 Ordered.HIGHEST_PRECEDENCE, Ordered.LOWEST_PRECEDENCE 로 결정합니다.
@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
class UserProfileExceptionHandler {
@ExceptionHandler(UserProfileException)
@ResponseBody
ResponseEntity<ErrorResponse> handleUserProfileException() {
....
}
}
@ControllerAdvice
@Order(Ordered.LOWEST_PRECEDENCE)
class DefaultExceptionHandler {
@ExceptionHandler(RuntimeException)
@ResponseBody
ResponseEntity<ErrorResponse> handleRuntimeException() {
....
}
}
728x90