2 回答

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超11個(gè)贊
在這里,您使用與請(qǐng)求正文和響應(yīng)正文相同的對(duì)象。這不是標(biāo)準(zhǔn)做法。
您應(yīng)該有單獨(dú)的請(qǐng)求/響應(yīng)對(duì)象。在請(qǐng)求對(duì)象中,您應(yīng)該只從用戶(hù)那里獲得您需要的信息。但是在響應(yīng)對(duì)象中,您應(yīng)該包含要在響應(yīng)中發(fā)送的信息以及驗(yàn)證信息,例如錯(cuò)誤詳細(xì)信息,其中包括錯(cuò)誤代碼和錯(cuò)誤描述,您可以使用它們向用戶(hù)顯示驗(yàn)證錯(cuò)誤。
希望這可以幫助。

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超3個(gè)贊
好吧,如果date_expiration
過(guò)期或identification_card
不符合客戶(hù)的要求,這就是商業(yè)失敗。
我喜歡用 來(lái)表示業(yè)務(wù)錯(cuò)誤HTTP 422 - Unprocessable Entity
。
如果您想在控制器中返回不同的對(duì)象,您可以將返回對(duì)象從 更改ResponseEntity<CreditCard>
為,但如果目的是返回錯(cuò)誤,我更喜歡在帶注釋的方法中使用 a 。ResponseEntity<Object>
ExceptionHandler
ControllerAdvice
正如我所說(shuō),這種情況是業(yè)務(wù)失?。ㄐ庞每ㄒ堰^(guò)期或?qū)Ξ?dāng)前用戶(hù)不適用)。
這是一個(gè)例子。會(huì)是這樣的:
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());
? ? }
}
如果信用卡過(guò)期,JSON 將呈現(xiàn)為:
{
? "timestamp": "2019-10-29T00:00:00+00:00",
? "reason": "The card is expired"
}
添加回答
舉報(bào)