如何处理lambda表达式中的异常

时间:2017-07-27 11:12:39

标签: java lambda optional

我有metohod MyService #create抛出CustomException。我在Optional#map中调用此方法,如下所示:

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,但结果我得到Operation成功且状态为200.如何在lambda中处理此异常并从异常返回消息?

1 个答案:

答案 0 :(得分:2)

您会捕获异常并返回var data = new Blob([response.data],{type: response.headers('Content-Type')}); FileSaver.saveAs(data, response.headers('content-filename'));

然后将其映射到new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST)

如果您希望仅在呼叫成功时才将new ResponseEntity<>("Operation successful", HttpStatus.CREATED)重写为:

new ResponseEntity<>("Operation successful", HttpStatus.CREATED)