Skip to main content
1-Visitor
December 6, 2019
Solved

Thingworx set a custom return code and response

  • December 6, 2019
  • 8 replies
  • 4507 views

Hello,

 

In a service I need to return an error with status code = 500 and return type JSON.

 

Actually my service returns JSON but the response I really get is "Error executing service getError. Message :: {"test":"error"} - See Script Error Log for more details." and what I want to get is just the JSON {"test":"error"}

 

I succeeded to have this work if I call a service on a resource but as soon as I call the service of the resource from a service of a Thing it doesn't work.

 

Any ideas?

 

Thanks

Best regards  

Best answer by TravisPickett

Hello,

 

It is not possible to specify the HTML return code from within a thing service.  In the case you provided you could do something like the following:

var result = {};
if(code >= 500)
{
 try
 {
 result.message = Resources["JSONErrorResource"].GetBadRequest(
 {content: {"plop": "error"}});
 result.status = "200";
 }
 catch( err )
 {
 logger.error( "The following error occured. " + err );
 result.status = "500";
 result.message = "Some Error message here";
 }
}
else
{
 result.status = "200";
 result.message = "ok";
}

This will return JSON in the following format:

{
 status:200 OR 500
 message:OK OR Custom error message OR Service response
}

 The calling application would then be responsible for checking the content returned for the "true" service status code and response message.

8 replies

22-Sapphire I
December 9, 2019

What does your actual code look like that sets the result when you want to return the error?

rbeck1-VisitorAuthor
1-Visitor
December 9, 2019

My service in the Thing calls this:

if(code >= 500){
	// result: JSON
var result = Resources["JSONErrorResource"].GetBadRequest({
	content: {"plop": "error"} /* JSON */
});
} else{
var result = {"plop": "ok"};
}

 Where Resources["JSONErrorResource"].GetBadRequest is a resource I created in Java which throws a InvalidRequestException

 

It was a test because my main purpose remains to reply an error 500 with a JSON content and not a string "Error executing service getError..." 

22-Sapphire I
December 9, 2019

use a logger statement to see what is actually being generated, also maybe add a try catch because perhaps something else is happening to generate an error you aren't expecting.