2017-07-27 78 views
0

我有metohod MyService#create引發CustomException。我稱之爲可選#地圖這個方法象下面這樣:如何處理lambda表達式中的異常

return Optional.ofNullable(obj) 
     .map(optObj -> { 
      try { 
       return myService.create(optObj); 
      } catch (CustomException e) { 
       return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); 
      } 
     }) 
     .map(created -> new ResponseEntity<>("Operation successful", HttpStatus.CREATED)) 
     .orElse(new ResponseEntity<>("Operation failed", HttpStatus.BAD_REQUEST)); 

當我調用此方法造成的異常,然後CustomException被逮住的論點,但結果我獲得成功的操作和狀態200.如何處理此異常lambda並從異常返回消息?

+0

沒有,沒有拋出異常。我想趕上並返回正確的結果 – user

+0

背後使用「可選」背後的原因是什麼?一個簡單的'if - then - else'就足夠了,也許與'try-catch'相配。 – Seelenvirtuose

+0

嘗試使用將負責處理異常的包裝方法 – sForSujit

回答

2

你確實發現異常並返回new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST)

然後將其映射到new ResponseEntity<>("Operation successful", HttpStatus.CREATED)

如果你想有new ResponseEntity<>("Operation successful", HttpStatus.CREATED)只有當調用成功,你的代碼改寫爲:在拉姆達

return Optional.ofNullable(obj) 
     .map(optObj -> { 
      try { 
       myService.create(optObj); 
       return new ResponseEntity<>("Operation successful", HttpStatus.CREATED); 
      } catch (CustomException e) { 
       return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); 
      } 
     }) 
     .orElse(new ResponseEntity<>("Operation failed", HttpStatus.BAD_REQUEST));