【问题标题】:what type your response entity should be to have different types of response您的响应实体应该是什么类型才能有不同类型的响应
【发布时间】:2021-08-24 16:23:07
【问题描述】:

我正在编写一个 Spring Boot 应用程序,在我的控制器中,我的一些 API 需要返回不同的类型。例如,当一切正常时,我想返回一个对象列表,在某些情况下我想返回错误消息。

例如,我有一个这样的 API:

@PostMapping("/transactions")
public ResponseEntity<Transaction> createTransaction(@RequestBody Transaction transaction) {
    try {

        User user = userRepository.findByUsername_(transaction.getUser().getUsername());
 
        Transaction _transaction = transactionRepository
                .save(new Transaction(transaction.getTransactionID(),user));

        return new ResponseEntity<>(_transaction, HttpStatus.CREATED);
    } catch (Exception e) {
        return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

我想生成返回的错误消息,我还希望我的 API 返回对象列表, 我们怎么能处理这样的事情?

【问题讨论】:

    标签: java spring-boot


    【解决方案1】:

    实现你想要的最好方法是使用 Spring 提供的异常处理。

    您可以让您的 API 声明它将返回什么。在您的情况下是Transaction。如果您想要这些项目的列表,您只需将 List&lt;Transaction&gt; 作为返回类型。

    至于错误处理,可以使用spring中的@ControllerAdvice来处理异常时的响应。

    @ControllerAdvice
    public class ErrorHandler {
    
        @ExceptionHandler(ApplicationException.class)
        public ResponseEntity handleApplicationException(ApplicationException e) {
            return ResponseEntity.status(e.getCustomError().getCode()).body(e.getCustomError());
        }
    }
    

    最好声明自己的应用程序异常

    @Getter
    @Setter
    public class ApplicationException extends RuntimeException  {
    
        private CustomError customError;
    
        public ApplicationException(CustomError customError){
            super();
            this.customError = customError;
        }
    }
    

    然后将您的错误消息作为对象作为 JSON 响应传递

    @Getter
    @Setter
    @NoArgsConstructor
    public class CustomError {
    
        private int code;
        private String message;
        private String cause;
    
        public CustomError(int code, String message, String cause) {
            this.code = code;
            this.message = message;
            this.cause = cause;
        }
    
        @Override
        public String toString() {
            return "CustomError{" +
                    "code=" + code +
                    ", message='" + message + '\'' +
                    ", cause='" + cause + '\'' +
                    '}';
        }
    }
    

    然后在你的控制器方法中你可以做

    @PostMapping("/transactions")
    public ResponseEntity<Transaction> createTransaction(@RequestBody Transaction transaction) {
        try {
    
            User user = userRepository.findByUsername_(transaction.getUser().getUsername());
     
            Transaction _transaction = transactionRepository
                    .save(new Transaction(transaction.getTransactionID(),user));
    
            return new ResponseEntity<>(_transaction, HttpStatus.CREATED);
        } catch (Exception e) {
            throw new ApplicationException( new CustomError(400, "Bad Request",
                            "Transaction is not allowed"));
        }
    }
    

    或您想要的任何其他自定义消息和错误

    【讨论】:

      猜你喜欢
      • 2013-07-29
      • 2015-02-08
      • 1970-01-01
      • 1970-01-01
      • 2013-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多