Spring Boot : comment gérer proprement les exceptions dans une API REST ?
poze 5 months ago118 gadefr
5
Mes contrôleurs ont des try/catch partout qui renvoient des ResponseEntity différents. Comment centraliser ?
Anviwònman:Spring Boot 3.3Java 21
Dyagnostik IA
Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.
poze 5 months ago
James Étienne 2.3k
1 Repons
4
✓✓ Repons yo aksepte
Utilise un @RestControllerAdvice avec des @ExceptionHandler, et le format standard ProblemDetail (RFC 9457) intégré à Spring 6 :
@RestControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
ProblemDetail notFound(ResourceNotFoundException ex) {
ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
pd.setTitle("Ressource introuvable");
return pd;
}
@ExceptionHandler(MethodArgumentNotValidException.class)
ProblemDetail invalid(MethodArgumentNotValidException ex) {
ProblemDetail pd = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
pd.setProperty("errors", ex.getBindingResult().getFieldErrors().stream()
.map(e -> Map.of("field", e.getField(), "message", e.getDefaultMessage())).toList());
return pd;
}
}
Active aussi spring.mvc.problemdetails.enabled=true pour que les erreurs internes de Spring suivent le même format. Tes contrôleurs se contentent alors de throw new ResourceNotFoundException(...).
Konekte pou di lòt moun si li te mache.
answered 5 months ago
Ruth Jean 2.2k
Sign in and verify your email to post an answer.