Spring Boot : comment gérer proprement les exceptions dans une API REST ?

asked 5 months ago121 viewsfr

5

Mes contrôleurs ont des try/catch partout qui renvoient des ResponseEntity différents. Comment centraliser ?

Environment:Spring Boot 3.3Java 21

AI diagnosis

AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.

asked 5 months ago

1 Answer

4
✓
✓ Accepted answer

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(...).

Sign in to tell others whether this worked.

answered 5 months ago

Sign in and verify your email to post an answer.