How can I handle exceptions with Spring Data Rest and the PagingAndSortingRepository?

夙愿已清 提交于 2019-12-03 17:39:33

问题


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. Revealing the @Query, etc.

// 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. Should I?

Thanks.


回答1:


You could use a global @ExceptionHandler with the @ControllerAdvice annotation. 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.

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




回答2:


You could use @ControllerAdvice and render the content your way. Here is tutorial if you need know how to work on ControllerAdvice, just remember to return HttpEntity



来源:https://stackoverflow.com/questions/21150688/how-can-i-handle-exceptions-with-spring-data-rest-and-the-pagingandsortingreposi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!