Junior — Middle
How can custom error handling be implemented in Spring to return correct responses instead of exceptions?
sobes.tech AI
Answer from AI
In Spring, to handle user errors and return correct responses instead of exceptions, the common approach is to use a global exception handler mechanism with the @ControllerAdvice annotation and methods annotated with @ExceptionHandler.
This allows intercepting exceptions that occur in controllers and forming custom response objects with the desired HTTP status and body.
Example:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(CustomNotFoundException.class)
public ResponseEntity<String> handleNotFound(CustomNotFoundException ex) {
return new ResponseEntity<>("Resource not found: " + ex.getMessage(), HttpStatus.NOT_FOUND);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGeneric(Exception ex) {
return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Thus, instead of an exception leading to a standard server error, the application returns a clear and controlled response to the client.