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

时间:2014-01-15 23:45:13

标签: 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);
}

这很有效。但是,如果客户端发送已形成的请求(例如,搜索不存在的字段),则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

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

{
    message:null,
    cause: {
        message: 'org.hibernate.QueryException: could not resolve property: blahblah...'
    }
}

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

感谢。

2 个答案:

答案 0 :(得分:4)

您可以使用带有@ExceptionHandler注释的全局@ControllerAdvice。基本上,您使用@ControllerAdvice批注定义要在类中使用@ExceptionHandler处理哪个Exception,然后实现在抛出异常时要执行的操作。

像这样:

@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
    }
}

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

答案 1 :(得分:0)

您可以使用@ControllerAdvice并按照自己的方式呈现内容。如果您需要了解如何使用ControllerAdvice,请参阅教程,只需记住返回HttpEntity