【问题标题】:Spring Data Rest exception handling - Return generic error responseSpring Data Rest 异常处理 - 返回通用错误响应
【发布时间】:2015-07-26 12:42:46
【问题描述】:

我想知道如何在 Spring Data Rest 中处理由于格式错误的请求或数据库崩溃而导致的内部服务器错误类型异常,例如 JPA 异常等。我做了一些研究,发现更好的方法是使用@ControllerAdvice,但找不到任何可行的示例。我看了这两个问题,但仍然没有答案。

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

global exception handling for rest exposed spring-data

有人可以帮助我提供一个工作示例,说明如何使用@ControllerAdvice 并在出现异常时将自定义错误响应写回客户端。

【问题讨论】:

    标签: spring spring-boot exception-handling spring-data-jpa spring-data-rest


    【解决方案1】:

    这是我对所有请求验证错误的处理方式,

    @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;
        }
    }
    

    ResponseBean 是我的应用程序特定类。

    对于 JPA 错误,异常是 RuntimeExceptions,顶级异常是 -org.springframework.dao.DataAccessException

    如果您希望向客户端发送通用消息,则无需捕获 - 在您的 DAO、服务或控制器层中重新抛出。只需像上面那样为DataAccessException 添加一个异常处理程序,你就完成了。

    如果您希望为特定异常为客户端设置特定消息,您需要编写一个扩展 DataAccessException 的应用程序特定异常层次结构,比如说 MyAppJPAException 。您需要在应用程序代码(在 DAO、服务或控制器层)中捕获 - DataAccessException 并重新抛出 MyAppJPAExceptionMyAppJPAException 应该有一个自定义消息字段,您应该在重新抛出之前设置自定义消息。在MyAppJPAException 处理程序中,您将该消息设置为响应,并且可以将 HTTP 状态设置为 - HttpStatus.INTERNAL_SERVER_ERROR

    【讨论】:

    【解决方案2】:

    你可以这样做:

    @ControllerAdvice(basePackageClasses = RepositoryRestExceptionHandler.class)
    public class GenericExceptionHandler {
    
        @ExceptionHandler
        ResponseEntity handle(Exception e) {
            return new ResponseEntity("Some message", new HttpHeaders(), HttpStatus.BAD_REQUEST);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-24
      • 2022-07-29
      • 1970-01-01
      • 2019-09-20
      • 2017-11-28
      • 2014-02-04
      • 1970-01-01
      • 2014-04-05
      相关资源
      最近更新 更多