Spring Data Rest exception handling - Return generic error response

99封情书 提交于 2019-12-03 11:04:10

问题


I want to know how can I handle internal server error type exceptions in Spring Data Rest such as JPA exceptions etc. due to a malformed request or a database crash. I did some research found that the better way to do this is by using @ControllerAdvice but couldn't find any working example of it. I looked at both these questions but they are still unanswered.

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

global exception handling for rest exposed spring-data

Can someone help me with a working example of how to use @ControllerAdvice and write a custom error response back to client whenever there is an exception.


回答1:


You can do it like this:

@ControllerAdvice(basePackageClasses = RepositoryRestExceptionHandler.class)
public class GenericExceptionHandler {

    @ExceptionHandler
    ResponseEntity handle(Exception e) {
        return new ResponseEntity("Some message", new HttpHeaders(), HttpStatus.BAD_REQUEST);
    }
}



回答2:


This is the way I do it for all request validation errors,

@RestControllerAdvice
public class ApplicationExceptionHandler {

     @ExceptionHandler
     @ResponseStatus(HttpStatus.BAD_REQUEST)
     public ResponseBean handle(MethodArgumentNotValidException exception){

        StringBuilder messages = new StringBuilder();
        ResponseBean response = new ResponseBean();

        int count = 1;
        for(ObjectError error:exception.getBindingResult().getAllErrors()){
            messages.append(" "+count+"."+error.getDefaultMessage());
            ++count;
        }

        response.setMessage(messages.toString());
        return response;
    }
}

where ResponseBean is my application specific class.

For JPA errors , exceptions are RuntimeExceptions and top level Exception is - org.springframework.dao.DataAccessException .

If you wish to send a generic message to client, there is no need to catch - rethrow in your DAO, Service or Controller Layer. Just add an exception handler as above for DataAccessException and you are done.

If you wish to set specific messages for client for specific exceptions, you need to write an application specific exception hierarchy extending DataAccessException , lets say MyAppJPAException . You need to catch - DataAccessException in your application code ( either at DAO, Service or Controller layer ) and re throw MyAppJPAException . MyAppJPAException should have a custom message field where you should set your custom message before re throwing. In MyAppJPAException handler, you set that message in response and can set HTTP Status as - HttpStatus.INTERNAL_SERVER_ERROR



来源:https://stackoverflow.com/questions/30245129/spring-data-rest-exception-handling-return-generic-error-response

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