Outbound REST call with timeout and error handling
Call an external API from a script with RESTMessageV2: a timeout, status checks, safe JSON parsing and useful logs, without leaking secrets.
October 1, 2026 · #restmessagev2 #integrations #error-handling
A REST call without a timeout or status check is an outage waiting to happen. This wraps the essentials in one reusable function.
function callApi(endpoint, method, payload) {
var rm = new sn_ws.RESTMessageV2();
rm.setEndpoint(endpoint);
rm.setHttpMethod(method || 'get');
rm.setRequestHeader('Accept', 'application/json');
rm.setRequestHeader('Content-Type', 'application/json');
rm.setHttpTimeout(10000); // 10 seconds
if (payload) rm.setRequestBody(JSON.stringify(payload));
var res = rm.execute();
var status = res.getStatusCode();
var text = res.getBody();
if (status < 200 || status >= 300) {
gs.warn('API call failed: ' + method + ' ' + endpoint + ' -> ' + status + ' ' + res.getErrorMessage());
return { ok: false, status: status };
}
try {
return { ok: true, status: status, data: text ? JSON.parse(text) : null };
} catch (e) {
gs.warn('API returned invalid JSON from ' + endpoint);
return { ok: false, status: status };
}
}
How it works
setHttpTimeout()stops a slow API from holding a transaction open.- Every non-2xx status is logged with the method and endpoint, never with tokens or payloads.
- JSON parsing is guarded, so a bad response can’t throw an unhandled error.
Gotchas
- For real integrations, define a REST Message record with credentials or a connection alias rather than hardcoding endpoints.
- Calls through a MID Server need
setMIDServer(). - In a business rule, run slow calls asynchronously (an async rule or a flow) so users aren’t kept waiting.
MIT licence. Provided as-is, without warranty. Test in a sub-production instance first.