@RequestMapping({"/direct/test"})
public ApiMessageBean telPay(Integer num) {
Agent agentById = commonAgentDao.getAgentById(99987876);
try {
return new ApiMessageBean(ApiResponseCodeEnum.OK,
Optional.ofNullable(agentById).orElseThrow(
() -> new ErrorCodeException(ResponseCodeEnum.FIND_CURRENT_ADMIN_FAILURE)));
} catch (Exception e) {
return new ApiMessageBean(ApiResponseCodeEnum.NO, e.getMessage());
}
// try {
// return Optional.ofNullable(this.apiMessageBean(num)).orElseThrow(
// () -> new ErrorCodeException(ResponseCodeEnum.FIND_CURRENT_ADMIN_FAILURE));
// } catch (Exception e) {
// return new ApiMessageBean(ApiResponseCodeEnum.NO, e.getMessage());
// }
}
private ApiMessageBean apiMessageBean(Integer num) {
if (num == 1) {
throw new ErrorCodeException(ResponseCodeEnum.NO, "出错啦");
}
if (num == 2) {
throw new NullPointerException("空指针啦");
}
return new ApiMessageBean(ApiResponseCodeEnum.OK);
}
- 注解掉的部分,是其他异常的判断,实际上,orElseThrow不会生效,抛异常会直接抛出,而不是走orElseThrow自定义的异常。
- 未注解的部分,如果为null,则会走orElseThrow的部分。
- 即,Optional.ofNullable仅可用于判断传入的对象是否为空指针,不可判断异常是否为空指针异常,或者其他的东西!!!