【发布时间】: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