Disons que j’ai un référentiel comme:
public interface MyRepository extends PagingAndSortingRepository { @Query("....") Page findByCustomField(@Param("customField") Ssortingng customField, Pageable pageable); }
Cela fonctionne très bien. Toutefois, si le client envoie une demande formée (par exemple, en recherchant un champ inexistant), Spring renvoie l’exception en tant que JSON. Révéler le @Query
, etc.
// This is OK http://example.com/data-rest/search/findByCustomField?customField=ABC // This is also OK because "secondField" is a valid column and is mapped via the Query http://example.com/data-rest/search/findByCustomField?customField=ABC&sort=secondField // This throws an exception and sends the exception to the client http://example.com/data-rest/search/findByCustomField?customField=ABC&sort=blahblah
Un exemple de l’exception levée et envoyée au client:
{ message:null, cause: { message: 'org.hibernate.QueryException: could not resolve property: blahblah...' } }
Comment puis-je gérer ces exceptions? Normalement, j’utilise @ExceptionHandler
pour mes contrôleurs MVC, mais je n’utilise pas de couche entre l’API Data Rest et le client. Devrais-je?
Merci.
Vous pouvez utiliser un @ExceptionHandler global avec l’annotation @ControllerAdvice . En gros, vous définissez quelle exception gérer avec @ExceptionHandler au sein de la classe avec l’annotation @ControllerAdvice, puis vous implémentez ce que vous voulez faire lorsque cette exception est levée.
Comme ça:
@ControllerAdvice(basePackageClasses = RepositoryRestExceptionHandler.class) public class GlobalExceptionHandler { @ExceptionHandler({QueryException.class}) public ResponseEntity
Voir aussi: http://www.ekiras.com/2016/02/how-to-do-exception-handling-in-springboot-rest-application.html
Vous pouvez utiliser @ControllerAdvice et rendre le contenu à votre manière. Voici un tutoriel si vous avez besoin de savoir comment utiliser ControllerAdvice
, n’oubliez pas de renvoyer HttpEntity