Spring provides a better way of handling exceptions, which is Controller Advice. This is a centralized place to handle all the application level exceptions.
Our Dogs Controller now looks clean and is free for any sort of handling exceptions
handleRunTimeException: This method handles all the RuntimeException and returns the status of INTERNAL_SERVER_ERROR. handleNotFoundException: This method handles DogsNotFoundException and returns NOT_FOUND. handleDogsServiceException: This method handles DogsServiceException and returns INTERNAL_SERVER_ERROR.
The key is to catch the checked exceptions in the application and throw RuntimeExceptions. Let these exceptions be thrown out of the Controller class, and then, Spring applies the ControllerAdvice to it.
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import static org.springframework.http.HttpStatus.NOT_FOUND;
@ControllerAdvice
@Slf4j
public class DogsServiceErrorAdvice {
@ExceptionHandler({RuntimeException.class})
public ResponseEntity<String> handleRunTimeException(RuntimeException e) {
return error(INTERNAL_SERVER_ERROR, e);
}
@ExceptionHandler({DogsNotFoundException.class})
public ResponseEntity<String> handleNotFoundException(DogsNotFoundException e) {
return error(NOT_FOUND, e);
}
@ExceptionHandler({DogsServiceException.class})
public ResponseEntity<String> handleDogsServiceException(DogsServiceException e){
return error(INTERNAL_SERVER_ERROR, e);
}
private ResponseEntity<String> error(HttpStatus status, Exception e) {
log.error("Exception : ", e);
return ResponseEntity.status(status).body(e.getMessage());
}
}
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
@ControllerAdvice
public class DogsServiceErrorAdvice {
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler({DogsNotFoundException.class})
public void handle(DogsNotFoundException e) {}
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler({DogsServiceException.class, SQLException.class, NullPointerException.class})
public void handle() {}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler({DogsServiceValidationException.class})
public void handle(DogsServiceValidationException e) {}
}