如何使用Spring Data Rest和PagingAndSortingRepository处理异常?

cbm*_*eks 12 java exception-handling spring-data spring-data-jpa spring-data-rest

假设我有一个类似的存储库:

public interface MyRepository extends PagingAndSortingRepository<MyEntity, String> {

    @Query("....")
    Page<MyEntity> findByCustomField(@Param("customField") String customField, Pageable pageable);
}
Run Code Online (Sandbox Code Playgroud)

这非常有效.但是,如果客户端发送已形成的请求(例如,搜索不存在的字段),则Spring将异常作为JSON返回.揭示@Query等等

// 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
Run Code Online (Sandbox Code Playgroud)

抛出并发送给客户端的异常示例:

{
    message:null,
    cause: {
        message: 'org.hibernate.QueryException: could not resolve property: blahblah...'
    }
}
Run Code Online (Sandbox Code Playgroud)

我该如何处理这些例外情况?通常,我使用的@ExceptionHandler是我的MVC控制器,但我没有使用Data Rest API和客户端之间的层.我是不是该?

谢谢.

Rap*_*edo 5

您可以将全局@ExceptionHandler@ControllerAdvice注释一起使用。基本上,您使用@ControllerAdvice 注释在类中定义要使用@ExceptionHandler 处理的异常,然后在抛出该异常时实现您想要执行的操作。

像这样:

@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
    }
}
Run Code Online (Sandbox Code Playgroud)

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