client.UploadString (Exception has been thrown by the target of an invocation)

I’m currently using a url printer for sms text, but I would like to get response codes. The ClickSend API needs specific headers. I found a few examples of this. using client.UploadString is giving me an error. If anyone has an idea that would be great.

No issues until it gets to

var data = client.UploadString(url,request);

https://developers.clicksend.com/docs/rest/v3/?shell#ClickSend-v3-API-SMS

Nevermind, I’m making it to hard on myself. Just used the helpers and it worked fine.

function send2() {

var url = "https://rest.clicksend.com/v3/sms/send";
var request = "{\"messages\": [ {\"body\":\"Test Message\",\"to\":\"+xxxxxxxxxxxxx\"} ] }";
var username = "username";
var password = "xxxxxxxxxxxxx";

var data = web.PostJson(url,request,username,password);

return data;
}

image

1 Like

aww and I just was able to catch the exception

System.Net.WebException: The remote server returned an error: (401) Unauthorized.

In the future you can use tryCatch to display exceptions thrown:

function test()
{
    var lib = host.lib("System");
    var client = new lib.System.Net.WebClient();
    var request = "{\"message\":[{\"source\":\"php\",\"body\":\"Jelly liquorice\",\"to\":\"+6141111111\"}]}";
    
    client.Headers.Add("Authorization", "Basic YXBpLXVzZXJuYW110mFwaS1wYXNzd29yZA==");
    client.Headers.Add("Content-Type", "application/json");
    
    var url = "https://rest.clicksend.com/v3/sms/send";
    
    var data;
    var hostException;
    var issuccessful = host.tryCatch
    (
        function()
        {
            var data = client.UploadString(url, request);
        },
        function(exception) 
        {
            hostException = exception;
            return true;
        }
    );
    
    if (isSuccessful)
    {
        return data;
    }
    else
    {
        return hostException;   
    }
}

else the debugger just shows this:

3 Likes

Thanks Memo. Thats great information. Looks like it was unauthorized. Thats odd that the authorization didn’t go through. I copied it directly from their site.

I used my actual credentials when using the helper. Either way, I really appreciate info like this.

1 Like

thank you very much. it makes my job easier.
I have a question:
is it possible to output in some way only the code and the error message, to work with him later?
ex.
if (error code == 401) {
return “Please log in”
}

the status code is in the Message property of the WebException and looks to be the inner exception of the inner exception.

I haven’t tested it, but it should be accessible as such:

    if (hostException.InnerException != null && hostException.InnerException.InnerException != null)
    {
        var msg = hostException.InnerException.InnerException.Message;
        
        if (msg.indexOf('401') !== -1)
        {
            return 'whatever message you want';
        }
    }
1 Like