-
[spring boot] 에러 핸들링 @ExceptionHandler @ControllerAdvicespring boot 2024. 1. 25. 00:05
Spring의 예외 처리방법
1. Controller내에서의 Error handling
package com.example.demo.controller; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; @RestController public class Controller { @PostMapping("/exception") public void exceptionTest() throws Exception { throw new Exception(); } @ExceptionHandler(value = Exception.class) public ResponseEntity<Map<String, String>> exceptionHandler() { HttpHeaders httpHeaders = new HttpHeaders(); HttpStatus httpStatus = HttpStatus.BAD_REQUEST; Map<String, String> map = new HashMap<>(); map.put("error type", httpStatus.getReasonPhrase()); map.put("status code", "400"); map.put("message", "error"); return new ResponseEntity<>(map, httpHeaders, httpStatus); } }
2. @ControllerAdvice를 사용한 예외 처리
package com.example.demo.exception; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.util.HashMap; import java.util.Map; @RestControllerAdvice // 예외 발생 시 json의 형태로 결과를 반환하기 위해서는 @RestControllerAdvice 사용 public class MyExceptionHandler { @ExceptionHandler(value = Exception.class) public ResponseEntity<Map<String, String>> exceptionHandler() { HttpHeaders httpHeaders = new HttpHeaders(); HttpStatus httpStatus = HttpStatus.BAD_REQUEST; Map<String, String> map = new HashMap<>(); map.put("error type", httpStatus.getReasonPhrase()); map.put("status code", "400"); map.put("message", "error"); return new ResponseEntity<>(map, httpHeaders, httpStatus); } }
두 방법을 보면 차이점이 뭐지 싶을 것이다.
두 방법의 차이점은 같은 에러 발생시 어떤 예외 처리를 우선 순으로 두는가 이다.
Controller와 ControllerAdvice 내에 둘다 동일한 ExceptionHandler가 존재한다면 Controller 내에 있는 ExceptionHandler가 우선순위를 갖는다.
'spring boot' 카테고리의 다른 글
[Spring boot] Lombok에 대해 알아보자 (1) 2024.02.12 [Spring boot] Logback에 대해서 알아보자. (0) 2024.02.12 [Spring Boot] ResponseEntity란? (0) 2024.01.24 [Spring] 다양한 매핑 방법 (1) 2024.01.22 spring security 403 Forbidden Error (0) 2023.01.12