web:framework:spring:exceptions

Gestion des Exceptions

Spring permet de définir la gestion des exceptions via un ExceptionHandler, qu'il est possible de mettre :

  • Dans un contrôleur
  • Dans le ControllerAdvice pour une gestion centralisée.

L'annotation @ExeptionHandler peut être associée à une ou plusieurs exceptions.

L'utilisation de ExceptioinHandler dans le ControllerAdvice permet de centraliser la gestion des exceptions :

@ControllerAdvice
public class MainAdvice {

    @ExceptionHandler({TodoNotFoundException.class, NoSuchElementException.class})
    public String handleTodoNotFoundException(RedirectAttributes attributes) {
        InfoMessage msg = InfoMessage.error("Erreur", "La tâche demandée n'existe pas");
        attributes.addFlashAttribute("msg", msg);
        return "redirect:/";
    }
...
}

<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-validation</artifactId> 
</dependency>

  • web/framework/spring/exceptions.txt
  • Dernière modification : il y a 2 jours
  • (modification externe)