如何使用Spring Data Rest和PagingAndSortingRepository处理exception?
假设我有一个类似的存储库:
public interface MyRepository extends PagingAndSortingRepository { @Query("....") Page findByCustomField(@Param("customField") String customField, Pageable pageable); }
这很好用。 但是,如果客户端发送已形成的请求(例如,搜索不存在的字段),则Spring将exception作为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
抛出exception并发送给客户端的示例:
{ message:null, cause: { message: 'org.hibernate.QueryException: could not resolve property: blahblah...' } }
我该如何处理这些例外? 通常,我将@ExceptionHandler
用于我的MVC控制器,但我没有在Data Rest API和客户端之间使用层。 我是不是该?
谢谢。
您可以将全局@ExceptionHandler与@ControllerAdvice批注一起使用。 基本上,您使用@ControllerAdvice批注定义要在类中使用@ExceptionHandler处理的Exception,然后实现在抛出exception时要执行的操作。
喜欢这个:
@ControllerAdvice(basePackageClasses = RepositoryRestExceptionHandler.class) public class GlobalExceptionHandler { @ExceptionHandler({QueryException.class}) public ResponseEntity
另见: http : //www.ekiras.com/2016/02/how-to-do-exception-handling-in-springboot-rest-application.html
您可以使用@ControllerAdvice并以您的方式呈现内容。 如果您需要知道如何使用ControllerAdvice
,请HttpEntity
教程,只需记住返回HttpEntity