Question MARK PONGONIS · 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

Comments

Stephen Canzano · Nov 9, 2023

In this case I think tSC represents a status that indicates was the HttpRequest able to reach the remote server, not specifically what the call successful or not and yes

http.HttpResponse.StatusCode 

will have values of 

200 

401

404

500

etc.

0
Pietro Di Leo · Nov 9, 2023

Hi, you can try something like this: 

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

// Analyze response codeIf '($$$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 statusSet 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) 

0
Ashok Kumar T · Nov 9, 2023

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.

0
Herman Slagman · Nov 10, 2023

It just what you define a 'success', from a pure HTTP standpoint *any* HTTP status code is a success, the server was able to return a status code.
If you want to check if a resource exists or not, a 404 is a perfectly successful response.

0