我是spring的新手,我正試圖弄清楚全域例外處理。我想實作的是,當一個請求帶有一個不存在的主鍵時,我想回傳一個HTTP_NO_CONTENT,其主體包括時間戳和上述請求的給定id。
以下是我的控制器建議
。
public class ControllerAdvisor {
public ResponseEntity<ResponseBody> handleNoLevelFoundException(NoLevelFoundException ex) {
ex.printStackTrace()。
ResponseBody error = new ResponseBody()。
error.setTime(Timestamp.from(Instant.now()))。
error.setMessage(ex.getMessage())。
return new ResponseEntity<>(error, HttpStatus.NO_CONTENT)。
}
而這些是我自定義的例外和responseBody
。public class NoLevelFoundException extends RuntimeException{
public NoLevelFoundException(int id){
super("No level with id " id " found!") 。
}
}
public class ResponseBody {
private Timestamp time;
private String message;
...
當我通過postman向一個不存在的專案發出請求時,我收到這樣的資訊。
使用return ResponseEntity.noContent().build();我仍然得到正確的狀態代碼,但我找不到任何方法來添加body。
我還嘗試了這段代碼
ResponseBody error = new ResponseBody() 。
error.setTime(Timestamp.from(Instant.now()))。
error.setMessage(ex.getMessage())。
return ResponseEntity.status(HttpStatus.NO_CONTENT).body(error)。
用這種方式,我明確地添加了body,但結果還是一樣。正確的HTTP狀態但是空的body。
#EDIT
這就是我如何在第一時間拋出錯誤的原因
第一個請求被RestContorller捕獲
public class LevelRestApi {
private ServiceLayer service。
呼叫服務層,檢查專案是否存在。我在這里拋出了錯誤。
呼叫服務層,檢查專案是否存在。
@Service
public class AlienInvadersServiceLayer implementsServiceLayer{
JpaRepository levelRepository。
@Autowired
public AlienInvadersServiceLayer(@Qualifier(value = "levelRepository") JpaRepository levelRepository){
this.levelRepository = levelRepository;
}
@Override
public Level getLevel(int levelId) {
Optional<Level> result = levelRepository.findById(levelId);
if (result.isPresent()){
return result.get();
}
else {
throw new NoLevelFoundException(levelId)。
}
}
uj5u.com熱心網友回復:
問題出在return new ResponseEntity<>(error, HttpStatus.NO_CONTENT);handleNoLevelFoundException方法。
當你說NO_CONTENT時,它只是清空了你的回應體,而且確實有意義。
我建議使用HttpStatus.NOT_FOUND代替。
所以你的代碼應該看起來像這樣
public ResponseEntity<ResponseBody> handleNoLevelFoundException( NoLevelFoundException ex) {
//其他代碼
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND)。
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/320011.html
標籤:
上一篇:在C#中獲得一個"空佇列"例外
