在这种情况下如何使用 lambda 避免 null?

How can I avoid null using lambda in this case?

下面的方法你已经看到了return根据phone号查询数据库中用户的所有信息如下

{
  "message": "The operation was successful.",
  "code": 200,
  "fileDetailResponseDtos": [
    {
      "phoneNumber": "550000000",
      "textMessage": "Message1",
      "createDateTime": "2021-10-20T15:45:27.277",
      "sender": "Anar",
      "status": 0,
      "originatry": 0
    },
    {
      "phoneNumber": "550000000",
      "textMessage": "Message2",
      "createDateTime": "2021-10-20T15:45:27.277",
      "sender": "Anar",
      "status": 0,
      "originatry": 0
    },
    {
      "phoneNumber": "550000000",
      "textMessage": "Message3",
      "createDateTime": "2021-10-20T15:45:27.277",
      "sender": "Anar",
      "status": 0,
      "originatry": 0
    }
  ]
}

但是,当我根据不在数据库中的 phone 号码执行操作时,它仍然是 return 第二部分而不是此消息。

{
  "message": "The operation was successful",
  "code": 200,
  "fileDetailResponseDtos": []
}

但我希望它在输出中看起来像这样。

{
  "message": "Unfortunately, no information was found for this number.",
  "code": 400,
}

是的,我知道不可能 return 列表为空。这里是我在dao层写的方法

执行无效操作时如何输出我想要的消息?

@Override
public List<FileDetail> getByPhoneNumberCBVersion(String phoneNumber) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<FileDetail> generateQueryWithMethods = criteriaBuilder.createQuery(FileDetail.class);
    Root<FileDetail> starsFrom = generateQueryWithMethods.from(FileDetail.class);
    generateQueryWithMethods.select(starsFrom);
    generateQueryWithMethods.where(criteriaBuilder.equal(starsFrom.get("phoneNumber"), phoneNumber));
    TypedQuery<FileDetail> query = entityManager.createQuery(generateQueryWithMethods);
    List<FileDetail> resultList = query.getResultList();
    return resultList;
}

如果 resultList 为空,则抛出异常并在 ControllerAdvice 中捕获并将消息转换为特定响应。

恕我直言:在 table 中列出所有数据时无需抛出异常。如果它是空的,你可以将它列出给客户端(UI,邮递员脚本...),状态代码为 200,列表为空。

抛出自定义 BadRequestException 时的 restcontrolleradvice 示例。

@RestControllerAdvice
public class ExceptionHandlerAdvice {
   @ExceptionHandler(value = BadRequestException.class)
    public ResponseEntity<ErrorResource> handleBadRequest(BadRequestException ex) {
        LOGGER.error(ex.getMessage(), ex);
        return ResponseEntity.status(ExceptionResponse.BAD_REQUEST.getStatus())
                .body(new ErrorResource(ExceptionResponse.BAD_REQUEST.getCode(),
                        String.format(ExceptionResponse.BAD_REQUEST.getMessage(), ex.getMessage())));
    }
}

如果 resultList 为空,则抛出异常,如下例所示。

if(CollectionUtils.isEmpty(resultList)) {
  throw new BadRequestException();
}