【问题标题】:How to catch null value on http response如何在http响应中捕获空值
【发布时间】:2020-07-20 14:49:10
【问题描述】:

我有以下代码方法,用于测试 MSGraph API 中的现有用户

public String getGuestUserId(String AuthToken,String userEmail){

    String _userId
    def http = new HTTPBuilder(graph_base_user_url + "?")

        http.request(GET) {

            requestContentType = ContentType.JSON
            //uri.query = [ $filter:"mail eq '$userEmail'"].toString()
            uri.query=[$filter:"mail eq '$userEmail'"]
           
            headers.'Authorization' = "Bearer " + AuthToken    

            response.success = { resp, json ->
                //as the retunr json alue is an array collection we need to get the first element as we request all time one record from the filter
                **_userId=json.value[0].id**
                                    
            }

            // user ID not found : error 404
            response.'404' = { resp ->       
                _userId = 'Not Found'
            }

        }
        _userId
    } 

当用户存在时,此方法可以正常工作,并且会从成功响应中正确返回用户 ID 属性。

我得到的问题是,如果用户不存在,则 ID 字段也不存在并且数组为空。

我怎样才能有效地处理这种情况并向调用者返回一个有意义的完整值,例如“用户不存在”

我在响应端尝试了一个 catch 异常,但似乎没有用

知道如何处理测试,例如如果 array[0] 为空或不包含任何 Id 属性,然后返回一些东西?

感谢您的帮助 问候

【问题讨论】:

  • 如果你的外部代码期望异常,也许只是抛出一个异常...response.'404' = { resp -> throw new Exception("User not found") }
  • 感谢@daggett 的回复,但问题是当没有找到用户时,http 响应为 Success 但 _userId=json.value[0] 的 Id 属性不存在,因为value[] 为空,如何检查?
  • if( json.value.size()>0 ) ?
  • if( json.value ){} 应该这样做

标签: groovy


【解决方案1】:

不捕获 NPE 似乎已被广泛接受。相反,应该检查某些内容是否为空。

在你的情况下:

  1. 你应该检查json.value是否不为空
  2. 您还应该检查id 是否不为空。

还请注意,在 lambdas 中处理异常总是很棘手。

您可以将代码更改为:

http.request(GET) {
  requestContentType = ContentType.JSON
  uri.query=[$filter:"mail eq '$userEmail'"]
       
  headers.'Authorization' = "Bearer " + AuthToken

  if (json.value && json.value[0].id) {
    response.success = { resp, json -> **_userId=json.value[0].id** }
  } else {
    // Here you can return generic error response, like the one below
    // or consider more granular error reporting
    response.'404' = { resp -> _userId = 'Not Found'}
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-15
    • 2016-01-29
    • 2017-02-26
    • 2020-06-28
    • 1970-01-01
    相关资源
    最近更新 更多