0

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?

user
  • 4,410
  • 16
  • 57
  • 83

1 Answers1

2

You do catch exception and return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST).

Then you map it to new ResponseEntity<>("Operation successful", HttpStatus.CREATED).

If you want to have new ResponseEntity<>("Operation successful", HttpStatus.CREATED) only if call is successful rewrite your code to:

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));
talex
  • 17,973
  • 3
  • 29
  • 66