【发布时间】: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