Spring Data Rest exception handling - Return generic error response

☆樱花仙子☆ 提交于 2019-12-03 00:34:49

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);
    }
}
Sabir Khan

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

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