[英]Spring Boot: Best way to return 503 HttpStatus in ResponseEntity if the DataSource is DOWN
[英]Best way to return ResponseEntity with data, empty and error in Spring Boot?
我正在尝试实现一种通用方法,该方法可用于我的 Spring Boot 应用程序中从 Service 到 Controller 的每种返回类型。 在搜索和阅读了几个线程和文章之后,我发现我需要一种带有@ControllerAdvice
和@ExceptionHandler
注释的方法。
作为例外,我创建了以下类:
@ControllerAdvice
public class FileUploadException extends ResponseEntityExceptionHandler {
@SuppressWarnings("rawtypes")
@ExceptionHandler(MaxUploadSizeExceededException.class)
public ResponseEntity handleMaxSizeException(MaxUploadSizeExceededException e) {
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED)
.body(new ResponseMessage("Too large!"));
}
}
但是,我不确定它是否可以以及我应该如何处理Optional.empty()
导致我的服务和控制器。 那么,您能否建议我一个适当的方法或给出一个用于异常、数据结果和Optional.empty()
结果的示例?
请注意,我有以下文章,但它们太旧了,我不确定这些方法是否仍然很好,或者新版本的 Spring Boot 是否有更好的方法等?
具体的异常处理程序:
@RestController
@RequestMapping("/products")
public class ProductController {
@Autowierd private ProductService productService;
@GetMapping("/{code}")
public ResponseEntity<Product> findByCode(@PathVariable String code) {
return productService.findByCode(code).map(ResponseEntity::ok).orElseThrow(() -> NoContentException::new);
}
@ExceptionHandler(NoContentException.class)
public ResponseEntity handleNoContent(NoContentException e) {
return ResponseEntity.status(HttpStatus.NO_CONTENT).body(new ResponseMessage("No data"));
}
}
或常见的 ExceptionHandler :
@RestController
@RequestMapping("/products")
public class ProductController {
@Autowierd private ProductService productService;
@GetMapping("/{code}")
public ResponseEntity<Product> findByCode(@PathVariable String code) {
return productService.findByCode(code).map(ResponseEntity::ok).orElseThrow(() -> NoContentException::new);
}
}
加:
@ControllerAdvice
public class CommonExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(MaxUploadSizeExceededException.class)
public ResponseEntity handleMaxSizeException(MaxUploadSizeExceededException e) {
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage("Too large!"));
}
@ExceptionHandler(NoContentException.class)
public ResponseEntity handleNoContent(NoContentException e) {
return ResponseEntity.status(HttpStatus.NO_CONTENT).body(new ResponseMessage("No data"));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.