如何修复带有queryStringParameters的异常?

huangapple go评论56阅读模式
英文:

How to fix Exception with queryStringParameters?

问题

我正在尝试读取GET请求参数:

如果没有参数,我会出现异常。

event = objectMapper.readTree(input);
JsonNode queryParameterMap = event.findValue("queryStringParameters");

然而,如果我使用 "queryParameters" 而不是 "queryStringParameters",我就不会出现异常。

如果没有参数,我应该如何返回null而不引发异常

final String keyParameter = Optional.ofNullable(queryParameterMap)
                .map(mapNode -> mapNode.get("my_key").asText())
                .orElse(null);

看起来异常是由映射阶段引发的。

英文:

I am trying to read GET request parameters:

I have an exception if there are no parameters.

event = objectMapper.readTree(input);
JsonNode queryParameterMap = event.findValue("queryStringParameters"); 

However, I have no exception if I use "queryParameters" instead of "queryStringParameters".

How could I return null with no exception if there are no parameters?

final String keyParameter = Optional.ofNullable(queryParameterMap)
                .map(mapNode -> mapNode.get("my_key").asText())
                .orElse(null);

It looks like Exception came from mapping stage.

答案1

得分: 2

我找到了一个解决方案。
我只是添加了一个空过滤器,现在一切都正常运行。

final String keyParameter = Optional.ofNullable(queryParameterMap)
                .filter(s -> !s.isEmpty())
                .map(mapNode -> mapNode.get("my_key").asText())
                .orElse(null);
英文:

I have found a solution.
I just added Empty filter and everything works now.

final String keyParameter = Optional.ofNullable(queryParameterMap)
                .filter(s -> !s.isEmpty())
                .map(mapNode -> mapNode.get("my_key").asText())
                .orElse(null);

huangapple
  • 本文由 发表于 2020年7月22日 16:31:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/63030039.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定