How to handle exceptions in lambda expressions

This question already has an answer here:

  • Java 8 Lambda function that throws exception?

    21 answers

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?

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));