Junior — Middle
What methods or error handling mechanisms do you use in REST controllers?
sobes.tech AI
Answer from AI
In Java REST controllers, the following methods are usually used for error handling:
- Using the
@ExceptionHandlerannotation in the controller or in a separate class with@ControllerAdvicefor centralized exception handling. - Returning appropriate HTTP statuses with error descriptions in the response body, for example, 400 for client errors, 500 for server errors.
- Creating custom exception classes for different error types (e.g.,
ResourceNotFoundException,ValidationException).
Example of exception handling with @ControllerAdvice:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleNotFound(ResourceNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGeneral(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal server error");
}
}
This approach allows separating error handling logic from business logic and ensures a uniform response format for errors.