You need to sign in to do that
Don't have an account?
degmo
Callout exception handling
Hi All,
I am working on a feature where a Salesforce record is submitted to an external service via a callout. There is a requirement that if the external service returns a response code that isn't a 200 or 201 or there is other connection issues, a status field on the record needs to be updated with the value 'Callout Failed'.
The only way I can think of it to put the logic that does the status update inside of the finally block. Was wondering if this is best pattern or other have different approaches.
I am working on a feature where a Salesforce record is submitted to an external service via a callout. There is a requirement that if the external service returns a response code that isn't a 200 or 201 or there is other connection issues, a status field on the record needs to be updated with the value 'Callout Failed'.
The only way I can think of it to put the logic that does the status update inside of the finally block. Was wondering if this is best pattern or other have different approaches.
@future(callout=true) public static void doPost(Id recId) { Boolean calloutFailed = false; try { HttpResponse response = sendToExternal(recId); if( response.getStatusCode != 200 || response.getStatusCode != 201) { calloutFailed = true; } } catch(exception e) { calloutFailed = true; Util.logError(e, 'Error inside doPost()'); } finally { if(calloutFailed) { List<custom_object__c> curr = [SELECT Id FROM custom_object__c WHERE Id =: recId); if(curr.size() > 0) { curr[0].status = 'callout failed'; update curr; } } } } public static HttpResponse sendToExternal(Id recordId) { Http http = new Http(); HttpRequest request = new HttpRequest(); request.setEndpoint('xxxx'); request.setMethod('POST'); request.setBody('xxxxxxxxxxxx'); try { Http response = http.send(request); return response; } catch (exception e) { throw e; } }
1. You can avoid calloutFailed variable
2. You can avoid if(calloutFailed) condition
Less vraiables, if conditions, loops and logic is always better. Also, finally is meant to put the code which should be executed in either case.