9

比方说,我有一个像仓库:如何使用Spring Data Rest和PagingAndSortingRepository处理异常?

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

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

谢谢。

回答

1

你可以使用一个全球@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

1

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

+1

链接到教程丢失 –