I have metohod MyService#create which throws CustomException. I call this method in Optional#map like below:
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));
And when I call this method with arguments which cause exception then CustomException is catched but in result I get Operation successful and status 200. How to handle this exception in lambda and return message from exception?