백엔드/SpringBoot
@ControllerAdvice:SpringBoot 예외 처리
정진킴
2024. 4. 4. 08:37
전역 예외 처리
- 전역 예외 처리는 중앙 위치에서 응용 프로그램의 예외를 처리하는것을 의미
- 전역 예외 처리기는 모든 컨트롤러에 대한 예외를 중앙에서처리하는데 유용
- 2가지 주석
- @ControllerAdvice : 전체 응용 프로그램에서 예외를 처리 할 수 있는 스프링의 스테레오 타입 주석의 특수한 형태
- @ExceptionHandler : 특정 예외가 throw 될 때마다 호출되는 메서드를 지정할 수 있어서 중앙 집중식으로 예외를 처리하고 사용자에게 일관된 응답을 제공
- 2가지 주석
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler({ ArithmeticException.class })
public ResponseEntity<Object> handleGlobalException(ArithmeticException exception) {
CustomError error = new CustomError();
error.setErrorCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
error.setMsg("Arithmatic exception thrown " + exception.getLocalizedMessage());
return ResponseEntity
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(error);
}
}
@GetMapping(value = "/user")
public Object user(@RequestParam(value = "userId") String userId) {
int calc = 10 / 0;
System.out.println(calc);
return ResponseEntity.status(HttpStatus.OK);
}
- 10 / 0 이 ArithmeticException 이므로 Global Exception 이 발생한다.
- ArithmeticException 이란 0 으로 나누기 하면 발생하는 에러