HTTP timeout catch

I am changing a plugin so as it works with a device source and several devices in it. The problem is that when a device is turned off the http.get call fails, shows a timeout and disconnects. I would like to catch this timeout to be able to skip that device and continue with the next one. I tried to use the “status” but the code never gets to that point, it always shows a timeout in the console.log before executing the “getSettings.status” shown below:

var getSettings = HttpGet(HostName, “settings”);
console.log("status getSettings = " + getSettings.status);

function HttpGet(HostName, attribute) {
return http.get(“http://” + HostName + “/” + attribute, {‘timeout’: 2000});
}

Could you please give me a hint about how to catch a timeout?
Thank you vey much.

Use a try-catch.

try {
    var getSettings = HttpGet(HostName, "settings");
    console.log("status getSettings = " + getSettings.status);
} catch (error) {
    console.log(error);
}

function HttpGet(HostName, attribute) {
    return http.get("http://" + HostName + "/" + attribute, { 'timeout': 2000 });
}

https://www.w3schools.com/js/js_errors.asp

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch

Bill, thanks a lot for the suggestion and the links, I really appreciate your time invested!

Unfortunately it still does not get the error when the device is not available? I tried several codes but I always get the following console.log output:

connected
— Trying getSettings

disconnected
connected
— Trying getSettings

disconnected

This is the code I am using:

console.log("— Trying getSettings");
try {
var getSettings = HttpGet(HostName, “settings”);
console.log("— getSettings status code = " + getSettings.status);
HttpOK = true;
} catch (error) {
console.log("— getSettings error = " + error);
HttpOK = false;
}

I am attaching the plugin:
ShellyHTTP.plugin (11.3 KB)

I do not know what I am doing wrong?
Please whenever you have a moment I would really appreciate if you could give me a hint.
Many thanks again!

Bill,
I just realized that the problem now is with the console.log("— getSettings error = " + error); statement.
Apparently the error might not be called this way in the console.log? I tried several options with no success, but if I take out the console.log statment the code works!
I wonder what will be the right attribute to error, to get an explanatory message?
Many thanks!

See if it works if you try “error.message”. In standard JS error handling, “error” is an object with a message property.

console.log("— getSettings error = " + error.message);
1 Like

Bill, it works! Thanks a lot!
I will post the new plugins with all the improvements.

1 Like