实现你想要的最好方法是使用 Spring 提供的异常处理。
您可以让您的 API 声明它将返回什么。在您的情况下是Transaction。如果您想要这些项目的列表,您只需将 List<Transaction> 作为返回类型。
至于错误处理,可以使用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"));
}
}
或您想要的任何其他自定义消息和错误