2 回答

TA貢獻1818條經驗 獲得超11個贊
在這里,您使用與請求正文和響應正文相同的對象。這不是標準做法。
您應該有單獨的請求/響應對象。在請求對象中,您應該只從用戶那里獲得您需要的信息。但是在響應對象中,您應該包含要在響應中發送的信息以及驗證信息,例如錯誤詳細信息,其中包括錯誤代碼和錯誤描述,您可以使用它們向用戶顯示驗證錯誤。
希望這可以幫助。

TA貢獻1836條經驗 獲得超3個贊
好吧,如果date_expiration
過期或identification_card
不符合客戶的要求,這就是商業失敗。
我喜歡用 來表示業務錯誤HTTP 422 - Unprocessable Entity
。
如果您想在控制器中返回不同的對象,您可以將返回對象從 更改ResponseEntity<CreditCard>
為,但如果目的是返回錯誤,我更喜歡在帶注釋的方法中使用 a 。ResponseEntity<Object>
ExceptionHandler
ControllerAdvice
正如我所說,這種情況是業務失敗(信用卡已過期或對當前用戶不適用)。
這是一個例子。會是這樣的:
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"
}
添加回答
舉報