I’m in the process of building a wrapper class for interacting with the API that makes some application specific things easier to write code for. I want to have my own Create/Update/QueryResults methods that first verify that the current session is still valid, and if necessary, refresh the session, before trying to execute the Create/Update/Query.
The difficulty I’m running into is how to properly detect an expired or otherwise invalid sessionId. In searching I found this post in which one of the answers recommends putting a try/catch around binding.getUserInfo() to detect INVALID_SESSION_ID errors, but I’m hoping someone can point me towards a better way to do it than calling binding.getUserInfo() every time a Create/Update/Query is run.
Thanks.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
As the poster wrote:
Now to check that the sessionId is still valid, you can simply make
any API call, catch the exception and deal with it as appropriate.
That means you can do something like this (using an interface):
public static SalesforceResult performAction (SalesforceAction sa) throws UnexpectedErrorFault { SalesforceResult sr; while(true) { try { return sa.execute(binding); } catch(UnexpectedErrorFault uef) { if(uef.ExceptionCode == ExceptionCode.INVALID_SESSION_ID) { reauthenticateUser(); } // report any other exception to caller throw uef; } } }
SalesforceAction is just an interface:
public interface SalesforceAction { public SalesforceResult execute(SforceClient binding) throws UnexpectedErrorFault; }
You can then create objects that implement the interface for executing an action; the performAction function is boilerplate that catches a session exception and attempts a restart after refreshing the session from a source (either by password, refresh token, sso, etc).
Implementing an action can be done like this:
public class QueryAction implements SalesforceAction { string queryString; public QueryAction(String query) { queryString = query; } public SalesforceResult execute(SforceClient binding) throws UnexpectedErrorFault { QueryResult result = binding.query(queryString); SalesforceResult saresult = new SalesforceResult(); saresult.results = new SObject[] { result.records }; return saresult; } }
SalesforceResult is simply an informational block that might look like this:
public class SalesforceResult { public bool isComplete, isSuccess; public SObject[][] results; public String[] errors; }
The exact structure will depend on what your boilerplate code calls for. The original answer had these elements abstracted, because they weren’t directly relevant to the question.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0