Here is how to implement ControllerAdvice in SpringBoot
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 org.springframework.web.context.request.WebRequest; import java.util.HashMap; import java.util.Map; @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(FirstException.class) public ResponseEntity<Map<String, String>> handleFirstException(FirstException ex, WebRequest request) { Map<String, String> response = new HashMap<>(); response.put("error", "FirstException occurred"); response.put("message", ex.getMessage()); return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); } @ExceptionHandler(SecondException.class) public ResponseEntity<Map<String, String>> handleSecondException(SecondException ex, WebRequest request) { Map<String, String> response = new HashMap<>(); response.put("error", "SecondException occurred"); response.put("message", ex.getMessage()); return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); } @ExceptionHandler(Exception.class) public ResponseEntity<Map<String, String>> handleAllOtherExceptions(Exception ex, WebRequest request) { Map<String, String> response = new HashMap<>(); response.put("error", "Unexpected error"); response.put("message", ex.getMessage()); return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); } }