Chapitre 1: Gestion des Exceptions
Introduction
Les exceptions sont le mécanisme Java pour signaler les erreurs. Bien les utiliser est essentiel pour créer des applications robustes et maintenables.
🎯 Objectifs du Chapitre
À la fin de ce chapitre, vous saurez:
- ✅ Différencier Checked et Unchecked exceptions
- ✅ Créer des exceptions personnalisées
- ✅ Organiser une hiérarchie d'exceptions
- ✅ Appliquer les bonnes pratiques
1. Rappel: Hiérarchie des Exceptions Java
Throwable
├── Error (ne pas attraper)
│ ├── OutOfMemoryError
│ └── StackOverflowError
└── Exception
├── Checked Exceptions (doivent être déclarées)
│ ├── IOException
│ └── SQLException
└── RuntimeException (Unchecked)
├── NullPointerException
├── IllegalArgumentException
└── Vos exceptions personnalisées
2. Checked vs Unchecked
Checked Exceptions
// Doivent être déclarées avec throws ou catchées
public void readFile(String path) throws IOException {
Files.readString(Path.of(path)); // IOException possible
}
// Ou
public void readFile(String path) {
try {
Files.readString(Path.of(path));
} catch (IOException e) {
// Gérer l'erreur
}
}
Quand utiliser? Erreurs récupérables (fichier manquant, réseau).
Unchecked Exceptions (RuntimeException)
// Pas besoin de déclarer
public User findById(Long id) {
if (id == null) {
throw new IllegalArgumentException("ID cannot be null");
}
return userRepository.findById(id)
.orElseThrow(() -> new UserNotFoundException(id));
}
Quand utiliser? Erreurs de programmation, violations de contrat.
En Spring Boot: Préférez Unchecked
// ❌ Lourd à utiliser
public User findById(Long id) throws UserNotFoundException {
// ...
}
// ✅ Plus fluide
public User findById(Long id) {
// Lève une RuntimeException si non trouvé
return userRepository.findById(id)
.orElseThrow(() -> new UserNotFoundException(id));
}
3. Créer des Exceptions Personnalisées
Exception Simple
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(Long id) {
super("User not found with ID: " + id);
}
public UserNotFoundException(String message) {
super(message);
}
}
Exception avec Données Supplémentaires
@Getter
public class ResourceNotFoundException extends RuntimeException {
private final String resourceType;
private final Object resourceId;
public ResourceNotFoundException(String resourceType, Object resourceId) {
super(String.format("%s not found with ID: %s", resourceType, resourceId));
this.resourceType = resourceType;
this.resourceId = resourceId;
}
}
// Utilisation
throw new ResourceNotFoundException("User", 123L);
throw new ResourceNotFoundException("Product", "SKU-001");
Exception avec Code d'Erreur
@Getter
public class BusinessException extends RuntimeException {
private final String errorCode;
private final Map<String, Object> details;
public BusinessException(String errorCode, String message) {
super(message);
this.errorCode = errorCode;
this.details = new HashMap<>();
}
public BusinessException(String errorCode, String message, Map<String, Object> details) {
super(message);
this.errorCode = errorCode;
this.details = details;
}
}
// Utilisation
throw new BusinessException(
"INSUFFICIENT_BALANCE",
"Insufficient balance for withdrawal",
Map.of("requested", 500, "available", 100)
);
4. Hiérarchie d'Exceptions Métier
Structure Recommandée
// Exception de base pour l'application
public abstract class ApplicationException extends RuntimeException {
private final String errorCode;
protected ApplicationException(String errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
protected ApplicationException(String errorCode, String message, Throwable cause) {
super(message, cause);
this.errorCode = errorCode;
}
public String getErrorCode() {
return errorCode;
}
}
Exceptions Spécifiques
// Ressource non trouvée (→ 404)
public class ResourceNotFoundException extends ApplicationException {
public ResourceNotFoundException(String resourceType, Object id) {
super("RESOURCE_NOT_FOUND",
String.format("%s with ID %s not found", resourceType, id));
}
}
// Validation échouée (→ 400)
public class ValidationException extends ApplicationException {
private final List<FieldError> errors;
public ValidationException(List<FieldError> errors) {
super("VALIDATION_FAILED", "Validation failed");
this.errors = errors;
}
}
// Conflit (→ 409)
public class ConflictException extends ApplicationException {
public ConflictException(String message) {
super("CONFLICT", message);
}
}
// Non autorisé (→ 403)
public class ForbiddenException extends ApplicationException {
public ForbiddenException(String message) {
super("FORBIDDEN", message);
}
}
// Erreur métier (→ 422)
public class BusinessRuleException extends ApplicationException {
public BusinessRuleException(String code, String message) {
super(code, message);
}
}
Diagramme
ApplicationException
├── ResourceNotFoundException → 404
├── ValidationException → 400
├── ConflictException → 409
├── ForbiddenException → 403
├── BusinessRuleException → 422
└── TechnicalException → 500
5. Exemples d'Utilisation
Dans un Service
@Service
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
public User findById(Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("User", id));
}
public User create(UserRequest request) {
// Vérifier l'unicité
if (userRepository.existsByEmail(request.getEmail())) {
throw new ConflictException("Email already in use: " + request.getEmail());
}
// Créer l'utilisateur
User user = new User();
user.setEmail(request.getEmail());
user.setName(request.getName());
return userRepository.save(user);
}
public void delete(Long id) {
User user = findById(id); // Lève ResourceNotFoundException si non trouvé
if (user.hasActiveOrders()) {
throw new BusinessRuleException(
"CANNOT_DELETE_USER_WITH_ORDERS",
"Cannot delete user with active orders"
);
}
userRepository.delete(user);
}
}
Dans un Controller (sans gestion centralisée)
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping("/{id}")
public ResponseEntity<User> getById(@PathVariable Long id) {
try {
User user = userService.findById(id);
return ResponseEntity.ok(user);
} catch (ResourceNotFoundException e) {
return ResponseEntity.notFound().build();
}
}
}
Problème: Répétition du try-catch dans chaque méthode!
Solution: @ControllerAdvice (chapitre suivant)
6. Bonnes Pratiques
✅ À Faire
// 1. Nommer clairement
public class InsufficientStockException extends BusinessRuleException { }
public class PaymentDeclinedException extends BusinessRuleException { }
// 2. Inclure le contexte
throw new ResourceNotFoundException("Product", productId);
// 3. Utiliser des codes d'erreur
throw new BusinessRuleException("ORDER_LIMIT_EXCEEDED", "...");
// 4. Chaîner les causes
try {
externalService.call();
} catch (ExternalServiceException e) {
throw new TechnicalException("External service failed", e);
}
❌ À Éviter
// 1. Exceptions génériques
throw new Exception("Something went wrong"); // ❌
// 2. Messages vides
throw new RuntimeException(); // ❌
// 3. Catch and ignore
try {
riskyOperation();
} catch (Exception e) {
// Silencieux - ❌ JAMAIS!
}
// 4. Exceptions pour le flux normal
try {
user = findById(id);
} catch (UserNotFoundException e) {
user = createUser(id); // ❌ Utiliser Optional à la place
}
Pattern: Optional vs Exception
// Pour "peut ne pas exister"
public Optional<User> findByEmail(String email) {
return userRepository.findByEmail(email);
}
// Pour "DOIT exister"
public User getById(Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("User", id));
}
7. Exceptions Spring Boot Natives
ResponseStatusException
@GetMapping("/{id}")
public User getById(@PathVariable Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(
HttpStatus.NOT_FOUND,
"User not found: " + id
));
}
Avantage: Simple, pas besoin de @ControllerAdvice Inconvénient: Moins flexible, pas de format personnalisé
@ResponseStatus sur Exception
@ResponseStatus(HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(Long id) {
super("User not found: " + id);
}
}
Avantage: Automatique Inconvénient: Format de réponse par défaut de Spring
8. Résumé
Types d'Exceptions
| Type | Héritage | Usage |
|---|---|---|
| Checked | Exception | Erreurs récupérables |
| Unchecked | RuntimeException | Erreurs métier, programmation |
Hiérarchie Recommandée
ApplicationException (abstract)
├── ResourceNotFoundException (404)
├── ValidationException (400)
├── ConflictException (409)
├── BusinessRuleException (422)
└── TechnicalException (500)
Checklist
✅ Exceptions héritent de RuntimeException
✅ Messages clairs et informatifs
✅ Codes d'erreur pour l'API
✅ Contexte inclus (ID, type de ressource)
✅ Causes chaînées pour le débogage
🎯 Prochaine Étape
Vous savez créer des exceptions. Maintenant, apprenons à les gérer globalement avec @ControllerAdvice.
➡️ Chapitre 2: @ControllerAdvice