好吧,如果date_expiration 已过期或identification_card 对客户不满意,这就是业务失败。
我喜欢用HTTP 422 - Unprocessable Entity 表示业务错误。见here
如果您想在控制器中返回不同的对象,您可以将返回对象从ResponseEntity<CreditCard> 更改为ResponseEntity<Object>,尽管如果目的是返回,我更喜欢在ControllerAdvice 注释方法中使用ExceptionHandler错误。
正如我所说,这种情况是业务失败(信用卡已过期或对当前用户不起作用)。
这是一个例子。会是这样的:
CardService.java
@Service
public class CardService {
// ..
public CreditCard registerCard(CreditCard card) throws BusinessException {
if(cardDoesntBehaveToUser(card, currentUser()))) // you have to get the current user
throw new BusinessException("This card doesn't behave to the current user");
if(isExpired(card)) // you have to do this logic. this is just an example
throw new BusinessException("The card is expired");
return cardRepository.save(card);
}
}
CardController.java
@PostMapping("/card")
public ResponseEntity<Object> payCard(@Valid@RequestBody CreditCard creditCard) throws BusinessException {
CreditCard creC = cardService.registerCard(creditCard);
return ResponseEntity.ok(creC);
}
BusinessException.java
public class BusinessException extends Exception {
private BusinessError error;
public BusinessError(String reason) {
this.error = new BusinessError(reason, new Date());
}
// getters and setters..
}
BusinessError.java
public class BusinessError {
private Date timestamp
private String reason;
public BusinessError(String Reason, Date timestamp) {
this.timestamp = timestamp;
this.reason = reason;
}
// getters and setters..
}
MyExceptionHandler.java
@ControllerAdvice
public class MyExceptionHandler extends ResponseEntityExceptionHandler {
// .. other handlers..
@ExceptionHandler({ BusinessException.class })
public ResponseEntity<Object> handleBusinessException(BusinessException ex) {
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(ex.getError());
}
}
如果信用卡过期,JSON会呈现为:
{
"timestamp": "2019-10-29T00:00:00+00:00",
"reason": "The card is expired"
}