티스토리 뷰
Spring
[Spring Boot] @ExceptionHandler 에서 동일한 Exception을 구분해서 처리하는 방법
snail voyager 2023. 11. 24. 17:05728x90
반응형
@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
반응형
'Spring' 카테고리의 다른 글
[Spring Boot] Spring Boot 2.7 이후 MustacheEnvironmentCollector deprecated (0) | 2024.03.11 |
---|---|
[Spring] Swagger Fail to load remote configuration 접속 불가 (0) | 2024.02.19 |
[Spring Boot] No spring.config.import property has been defined (1) | 2023.11.23 |
[Spring Boot] 2.7.8 버전 이후 Amazon RDS Aurora MySQL JDBC Driver 변경 (0) | 2023.11.21 |
[Spring] Swagger CORS 이슈 (0) | 2023.11.09 |
반응형
300x250