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

问题描述 投票:0回答:1

我正在尝试实现一种通用方法,可用于我的 Spring Boot 应用程序中从服务到控制器的每种返回类型。在搜索和阅读多个线程和文章后,我发现我需要一种带有

@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 中的异常处理

java spring spring-boot rest spring-mvc
1个回答
1
投票

具体异常处理程序:

@RestController
@RequestMapping("/products")
public class ProductController {

  @Autowired 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"));
   }
}

常用异常处理程序:

@RestController
@RequestMapping("/products")
public class ProductController {

  @Autowired 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"));
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.