cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
Showing results for 
Search instead for 
Did you mean: 

Community Tip - Did you know you can set a signature that will be added to all your posts? Set it here! X

Return in the middle of a service

ngarner
1-Newbie

Return in the middle of a service

Hello,

I'm writing a service where I need to exit/return execution based on a programmatic decision.  For example:

if (var < 10)

{

  return/exit

}

continue execution

Thingworx throws an error when saving a service if you put "return" in the code.  What's the proper way to exit a service in the middle of execution?

Thank you,

Nick

6 REPLIES 6

There's no way of doing it, you need to put on if/else conditions.

For some special cases I use a "fake" throw exception:

throw "MESSAGE";

But I don't recommend you on using it, as it generates nasty logger messages, it would be good that they implement a way of doing both:

  • Return before the end of the service
  • Throw Exceptions

Carles.

vmihai
1-Newbie
(To:ngarner)

Hi,

I usually handle this by doing everything that I want to do in the if. So if the condition is not met, the service simply doesn't do anything and the call ends.

In your situation I would use

if ( var > 10 )

{

     // implement your code here

}

I also usually return some error messages if I need to show UI feedback, when the condition is not met. For example when I need to validate if all required fields have been inputted in a  form created with ThingWorx.

Hope this helps,

Veronica

PaiChung
22-Sapphire I
(To:ngarner)

Also consider try/catch/throw (besides if/else)

wrap the service body in an immediately invoked function.

original:

do stuff

if (my_var < 10)

{

     return; // fails

}

continue execution

wrapped:

var result = (function() {

     do stuff

     if(my_var < 10)

     {

          return; // works now.

     }

     continue execution

})();

Great, thank you, everyone.

Nick

Hi,

I've discovered another way with javascript of doing it:

labelName:

{

      // -- your code

      break labelName; // -- it will jump until the end of the brakets.

     // -- other conditional code

}


Best Regards,

Carles.

Top Tags