[英]How can I handle exceptions with Spring Data Rest and the PagingAndSortingRepository?
Let's say I have a repository like: 假设我有一个类似的存储库:
public interface MyRepository extends PagingAndSortingRepository<MyEntity, String> {
@Query("....")
Page<MyEntity> findByCustomField(@Param("customField") String customField, Pageable pageable);
}
This works great. 这非常有效。 However, if the client sends a formed request (say, searching on a field that does not exist), then Spring returns the exception as JSON.
但是,如果客户端发送已形成的请求(例如,搜索不存在的字段),则Spring将异常作为JSON返回。 Revealing the
@Query
, etc. 揭示
@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
An example of the exception thrown and sent to client: 抛出并发送给客户端的异常示例:
{
message:null,
cause: {
message: 'org.hibernate.QueryException: could not resolve property: blahblah...'
}
}
How can I handle those exceptions? 我该如何处理这些例外情况? Normally, I use the
@ExceptionHandler
for my MVC controllers but I'm not using a layer between the Data Rest API and the client. 通常,我将
@ExceptionHandler
用于我的MVC控制器,但我没有在Data Rest API和客户端之间使用层。 Should I? 我是不是该?
Thanks. 谢谢。
You could use a global @ExceptionHandler with the @ControllerAdvice annotation. 您可以将全局@ExceptionHandler与@ControllerAdvice批注一起使用。 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.
基本上,您使用@ControllerAdvice批注定义要在类中使用@ExceptionHandler处理的Exception,然后实现在抛出异常时要执行的操作。
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 另见: http : //www.ekiras.com/2016/02/how-to-do-exception-handling-in-springboot-rest-application.html
You could use @ControllerAdvice and render the content your way. 您可以使用@ControllerAdvice并以您的方式呈现内容。 Here is tutorial if you need know how to work on
ControllerAdvice
, just remember to return HttpEntity
如果你需要知道如何在
ControllerAdvice
上工作,这是教程,只记得返回HttpEntity
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.