繁体   English   中英

Spring Boot 中@RestController 的通用响应?

[英]Generic response for @RestController in Spring Boot?

在我的 Spring Boot 应用程序中,我只是第一次使用Optional ,在检查了几个项目和主题之后,现在我正在尝试构建一种方法,如下所示:


存储库:

Optional<Employee> findByEmail(String email);

服务:

public Response findByEmail(String email) {
    return employeeRepository.findByEmail(email)
            // if record is found, I think no need to return status or message
            .map(e -> Response.builder().data(e).build()) 
            .orElseGet(() -> Response.builder().status(404)
                .data(null).message("Not found!").build());
}

回复:

@Data
@Builder
public class Response {
    private int status;
    private Object data;
    private String message;
}

控制器:

@GetMapping("/employees/{email}")
public ResponseEntity<Response> findByEmail(@PathVariable String email) {
    final Response response = employeeService.findByEmail(email);
    return ResponseEntity
            .status(response.getStatus())

            .body(response.getMessage(), response.getData()); 
            // throws "Expected 1 arguments but found 2" error
}

以下是我需要澄清的几点:

1.这是对 Spring Boot 应用程序中的所有Optional类型使用公共响应的正确方法吗? 如果不是,我应该如何更改它(我想从服务返回一个共同的响应)?

2.如何修复Controller中抛出“Expected 1 arguments but found 2”的错误?

根据我上面的评论-您正在混合关注点。 服务应该只关心业务逻辑(例如,不关心 HTTP 状态代码)。 那是管制员的工作。 Optional 的使用是正确的,但服务层的 Response 返回类型不正确。 如果找不到资源,Spring boot 中的 Rest Controller 也会自动处理诸如 Not Found 之类的错误。 如果您想添加自定义逻辑并准备通用响应,请包含适当的异常处理,例如 @ControllerAdvice(它允许您重用控制器的异常)。

例如,解决方案之一是抛出NoSuchElementException 这是说明性的,如果您想以通用方式处理其他此类情况(例如,空指针、内部服务器错误、以更自定义方式的身份验证错误),这将适用。

public Employee findByEmail(String email) {
    return employeeRepository.findByEmail(email) //assuming findByEmail is returning an Optional<Employee>, otherwise - simply use a null check.
            .orElseThrow(NoSuchElementException::new)
}

在@ControllerAdvice 类中

  @ExceptionHandler(NoSuchElementException.class)
  @ResponseBody
  @Order(Ordered.HIGHEST_PRECEDENCE)
  public final ResponseEntity<APIResponseErrorContainer> handleNotFound(
      NoSuchElementException ex) {
// log exception here if you wish to
    return new ResponseEntity<>(createCustomResponseBody(),  HttpStatus.NOT_FOUND);
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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