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?

3
  • No, there is throwing exception in lambda. I want to catch and return right result Commented Jul 27, 2017 at 11:16
  • What is the reason behind using Optional at all? A simple if - then - else is enough here, maybe in companion with a try - catch. Commented Jul 27, 2017 at 11:16
  • try using wrapper method that will be responsible for handling the exception Commented Jul 27, 2017 at 11:17

1 Answer 1

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));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.