Question
· Nov 9, 2023

check if %Net.HttpRequest.HttpResponse.StatusCode is success

Is there a function that will check if an http request was successful or not? Maybe something similar to c# respose.IsSuccessStatusCode? %Status still returns success even if the response status code equals say 404.

Ex.

http=##class(%Net.HttpRequest).%New()
http.Server="example.com"
tsc = http.Get()   
http.HttpResponse.StatusCode    <== this is where i would like to check the status without having to write a custom function

Product version: IRIS 2022.1
Discussion (4)4
Log in or sign up to continue

Hi, you can try something like this: 

Set sc = $$$OK
// Send a GET request
Set messageStatus = httpRequest.Get()

// Analyze response code
If '($$$ISERR(messageStatus)) {
    If httpRequest.HttpResponse.StatusCode = 200 {
        // If a positive response was received 
        // ...
        // ...
    } ElseIf httpRequest.HttpResponse.StatusCode = 404 {
        // Manage an HTTP status error
        // ...
        // ...
        // If you want a custom error status
        Set ErrorText = "This is a string that contains your custom error text"
        Set sc = $$$ERROR(ErrorCode, ErrorText)
    } Else {
        // You can manage other HTTP codes here
    } 
} Else {
    If '($ISOBJECT(httpRequest.HttpResponse.StatusCode)){
        // Manage an error raised if the endpoint couldn't be reached or if you didn't get a response in time
        // ...
        // ...
        Set ErrorText = "This is a string that contains your custom error text"
        Set sc = $$$ERROR(ErrorCode, ErrorText)
    }
}

Return sc

You can manage any status code in the way you prefer (not just code 200 or 404) 

Hello @MARK PONGONIS

Get/Post/Put any method will return status if error while executing otherwise return 1. The HttpResponse object property actually contains the response details such as status code, content length, content type, response etc... 

So, As you mentioned the code is "http.HttpResponse.StatusCode" is used to get the status code of the response.