How can I handle exceptions with Spring Data Rest and the PagingAndSortingRepository?

前端 未结 2 467
逝去的感伤
逝去的感伤 2021-02-07 20:36

Let\'s say I have a repository like:

public interface MyRepository extends PagingAndSortingRepository {

    @Query(\"....\")
    Page<         


        
相关标签:
2条回答
  • 2021-02-07 21:09

    You could use @ControllerAdvice and render the content your way. Here is tutorial if you need know how to work on ControllerAdvice, just remember to return HttpEntity

    0 讨论(0)
  • 2021-02-07 21:23

    You could use a global @ExceptionHandler with the @ControllerAdvice annotation. Basically, you define which Exception to handle with @ExceptionHandler within the class with @ControllerAdvice annotation, and then you implement what you want to do when that exception is thrown.

    Like this:

    @ControllerAdvice(basePackageClasses = RepositoryRestExceptionHandler.class)
    public class GlobalExceptionHandler {
    
        @ExceptionHandler({QueryException.class})
        public ResponseEntity<Map<String, String>> yourExceptionHandler(QueryException e) {
            Map<String, String> response = new HashMap<String, String>();
            response.put("message", "Bad Request");
            return new ResponseEntity<Map<String, String>>(response, HttpStatus.BAD_REQUEST); //Bad Request example
        }
    }
    

    See also: http://www.ekiras.com/2016/02/how-to-do-exception-handling-in-springboot-rest-application.html

    0 讨论(0)
提交回复
热议问题