2017-07-27 80 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));