繁体   English   中英

在 Spring Boot 中返回带有数据、空和错误的 ResponseEntity 的最佳方法?

[英]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 是否有更好的方法等?

Spring Boot REST API 错误处理指南

Spring MVC 中的异常处理

具体的异常处理程序:

@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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM