httpGet and handling a 401 response


(Chris) #1

I have a DTH makes a web services call to an external service, but I am trying to add some additional logic on how it should handle a 401 response (i.e the user token is no longer valid in this case). My ‘if’ statement looks for a 200 response (this works fine), then I added an ‘else if’ statement to look for a 401, but the run crashes with “groovyx.net.http.ResponseParseException: Unauthorized” when the web service returns a 401. It doesn’t seem to run past the httpGet, as I don’t even get my debug code “log.debug “Response Status = ${resp.status}”” in the live log. How can I properly parse a 401 response? The current code, with all the actions removed for simplicity:

      try {
  	log.debug "Starting HTTP GET request to Whistle API"
	httpGet(params) { resp ->
    		log.debug "Response Status = ${resp.status}"
            
    	if(resp.status == 200) {
        	log.debug "Request to Whistle API was OK, parsing data"
                // do some stuff
            
    	else if(resp.status == 401) {
    		log.error "Request got HTTP status ${resp.status}"
            log.info "Whistle token expired, requesting new token"
           // do some other stuff
    	}
        else {
    		log.error "Request got HTTP status ${resp.status}"
                // any other error code
    	}
  
    }
} catch(e)
{
	log.debug e
}
 }

I’ve also tried looking for the specific error in the catch, but that doesn’t seem to work either:

    } catch(e) {
	if (e.equals("groovyx.net.http.ResponseParseException: Unauthorized")) {
    log.debug "User unauthorized, requesting new token"
     // do something
    }
    else {
    log.error "Something went wrong with the API call $e"
    }

(Chris) #2

Figured it out, if anyone has the same issue…

 } catch(e) {
	if (e.message.equals("Unauthorized")) {
    log.debug "User unauthorized, requesting new token"
    doSomething()
    }
    else {
    log.error "Something went wrong with the API call $e"
    }