【问题标题】:Java Spring Boot: Exception HandlingJava Spring Boot:异常处理
【发布时间】:2022-11-22 07:13:41
【问题描述】:

Web 服务的 Java Spring Boot 风格有点新——所以请保持温和。为什么大多数 Spring Boot Controller 示例不显示任何被捕获的异常?我看到我的一些开发人员同事经常这样做。答案是:这是一个共同的惯例。但为什么。我是否缺少使用 Spring Boot 创建的 Web 服务的关键概念?

例如:

@PostMapping(path = "/sampleEndpoint/v1/myEndpoint", produces = "application/json")
public ResponseEntity<String> myEndpoint(@RequestBody MyEndpointRequest myEndpointRequest) {
    
     MyEndpointResponse response = someService.myEndpoint(myEndpointRequest);
     return new ResponseEntity<>(response, HttpStatus.OK);
}

我想,就架构而言,您至少会添加一个带有日志记录的 try/catch 块,并抛出一个带有异常消息的新异常:

@PostMapping(path = "/sampleEndpoint/v1/myEndpoint", produces = "application/json")
public ResponseEntity<String> myEndpoint(@RequestBody MyEndpointRequest myEndpointRequest) {


  try{  
       MyEndpointResponse response = someService.myEndpoint(myEndpointRequest);
       return new ResponseEntity<>(response, HttpStatus.OK);

  }catch(Exception ex){
    //Your favorite logger:
    log.error("STACK_TRACE: {}", StaticClass.stackTraceToString(ex));

    //throw exception for calling or consuming system/application:
    throw new MiscException(ex.getMessage());
  }
}

有几件事可以为这个问题提供背景信息(观察):

  • 使用多个数据源:几个数据库和一些其他网络服务(为我们的客户提供一站式获取数据的地方。
  • 将此 Web 服务与潜在的 4 种不同的客户端/表示层类型的应用程序一起使用。
  • 我的团队想要捕获从我们利用的数据源发出的意外异常……并记录它们。

【问题讨论】:

    标签: java spring-boot web-services


    【解决方案1】:

    好吧,由开发人员实施捕获异常机制。但最好为此定义异常类型和错误代码/消息。假设您有一个端点使用 id 获取产品,但没有具有该 id 的产品,在这种情况下,客户端将收到 http 500 代码和 internal server error 消息。这会让用户和开发人员感到困惑,不知道该错误的真正原因是什么。

    所以要防止这些,您可以从 @ControllerAdvice 注释中获得帮助,这将允许将异常处理程序应用于多个或所有控制器。 首先,您将定义自定义异常,例如:

    public class ProductNotFoundException extends RuntimeException {
    
        public ProductNotFoundException(Long id) {
    
            super(String.format("Product with id %d not found", id));
        }
    }
    

    然后你可以定义你的ControllerAdvice类:

    @ControllerAdvice
    public class ExceptionHandler extends ResponseEntityExceptionHandler {
    
     @ExceptionHandler(ProductNotFound.class)
        public ResponseEntity<Object> handleProductNotFoundException(
            ProductNotFoundException ex, WebRequest request) {
    
            Map<String, Object> body = new LinkedHashMap<>();
            body.put("timestamp", LocalDateTime.now());
            body.put("message", "Product not found");
    
            return new ResponseEntity<>(body, HttpStatus.NOT_FOUND);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-09-29
      • 2023-03-28
      • 2018-03-16
      • 2020-10-10
      • 2015-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-09
      相关资源
      最近更新 更多