Spring
[Spring Boot] @ExceptionHandler 에서 동일한 Exception을 구분해서 처리하는 방법
snail voyager
2023. 11. 24. 17:05
728x90
반응형
@ControllerAdvice의 basePackages, annotations 속성으로 Controller 별로 Exception을 구분해서 처리할 수 있지만
URL Path 별로 구분하기는 어렵다.
아래처럼 동일 Exception을 구분해서 처리할 때는 @RequestMapping 으로 URL 을 구분할 수 있다.
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@RequestMapping("/api/**") // Specify the URL path pattern
public ResponseEntity<String> handleApiExceptions(HttpServletRequest request, Exception ex) {
// Handle exceptions for paths starting with "/api/"
// Custom logic to handle the exception
return new ResponseEntity<>("Error in API: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(Exception.class)
@RequestMapping("/web/**") // Another URL path pattern
public ResponseEntity<String> handleWebExceptions(HttpServletRequest request, Exception ex) {
// Handle exceptions for paths starting with "/web/"
// Custom logic to handle the exception
return new ResponseEntity<>("Error in Web: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
하지만 @ControllerAdvice의 basePackages 설정이 있다면 아래와 같은 에러가 발생된다.
Ambiguous @ExceptionHandler method mapped error occurs
@ControllerAdvice의 basePackages 설정을 사용해야한다면 @ExceptionHandler 메서드에서 requestURI로 구분하여 처리해야한다.
@ControllerAdvice(basePackages = "com.example.controllers")
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleExceptions(HttpServletRequest request, Exception ex) {
String requestURI = request.getRequestURI();
if (requestURI.startsWith("/api/")) {
// Handle API-related exceptions
return new ResponseEntity<>("Error in API: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
} else if (requestURI.startsWith("/web/")) {
// Handle web-related exceptions
return new ResponseEntity<>("Error in Web: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
} else {
// Handle other cases or provide a default behavior
return new ResponseEntity<>("Error: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
728x90
반응형