I am using Spring Boot framework for my backend application and Keycloak for my user and access management system. I have a problem regarding creating a costume exception handler for 403 forbidden error.
I already read this link and this link. These questions are about creating custom message when 403 error is raised. Both of the answers did not help me since I have a general exception handler.
Without any general exception handler, I get proper 401 and 403 responses regarding unauthorized tokens. But I want to have a general exception handler for unexpected errors. Following is my general exception handler:
@ExceptionHandler(value = Exception.class)
public ResponseEntity<String> generalExceptionHandler(Exception e) {
log.error(e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("General Error");
}
Without any other exception handler all situations that result in 401 or 403 response are handled by my generalExceptionHandler, which is not preferred. Since I want to send the proper message to the frontend in case of occurrence of 401 or 403 errors.
Therefore I developed an exception handler for Access denied exception like following:
@ExceptionHandler(value = AccessDeniedException.class)
public ResponseEntity<String> accessDeniedExceptionHandler(Exception e) {
log.error(e.getMessage());
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Access is denied"));
}
In this step all situations regarding the 401 situation are handled successfully with accessDeniedExceptionHandler.
The problem is that, situations regarding 403 Forbidden now are handled by accessDeniedExceptionHandler too. Since I want to send the proper message to frontend in case of 403 situation, I want to have a separate handler for this case. The reason relies in importance of distinguishing 401 and 403 errors in my software.
Can somebody please help me to fix this problem?