12

假设我有一个存储库,例如:

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 和客户端之间的层。我是不是该?

谢谢。

4

2 回答 2

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

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

于 2017-06-16T05:01:04.577 回答
1

您可以使用@ControllerAdvice并以您的方式呈现内容。这是教程,如果您需要知道如何工作ControllerAdvice,请记住返回HttpEntity

于 2014-01-27T21:44:31.590 回答