Jyothi
Jyothi

Reputation: 97

How to set HTTP status code for custom Thingworx service

Not able to set HTTP Status code for a custom ThingWorx service.

I need to send appropriate HTTP status code for error conditions in my Thingworx service. When I use GenericHTTPException, it sets the right code, but it prepends "Unable to Invoke Service" to my JSON response and that does not work for the AJAX client. I should be able to send pure JSON response along with the right HTTP status code

@ThingworxServiceDefinition(name = "GetServiceProviderHeirarchy", category = "PTC")
     @ThingworxServiceResult(name = "result", baseType = "JSON")
     public JSON GetServiceProviderHeirarchy(
                    @ThingworxServiceParameter(name = "seedURI", baseType = "STRING")String seedURI,
                    @ThingworxServiceParameter(name = "depth", baseType = "INTEGER")Integer depth,
                    @ThingworxServiceParameter(name = "resourceType", baseType = "STRING")String resourceType,
                    @ThingworxServiceParameter(name = "serverName", baseType = "STRING")String serverName)
                                throws Exception { 

     if(serverName == null || serverName.isEmpty()){
         JSONObject jsonErrObject = new JSONObject();
         jsonErrObject.put("message", "Values to input parameter serverName  is missing");
         logger.error("serverName is not provided");
         throw new InvalidRequestException(jsonErrObject.toString(), RESTAPIConstants.StatusCode.STATUS_BAD_REQUEST);
     }
}

Actual result:

Unable to Invoke Service GetServiceProviderHeirarchy on UpstreamOslcDataServicesThing : {"message":"No Configuration found for resource type RequirementResourc. Please contact your administrator."}

Expected result:

{"message":"No Configuration found for resource type RequirementResourc. Please contact your administrator."}

Upvotes: 1

Views: 383

Answers (1)

Unni Kris
Unni Kris

Reputation: 3105

One possible option would be to include the jax-rs libraries as a ThingWorx resource and throw those specific exceptions as required. Say for bad request you can throw javax.ws.rs.BadRequestException'.

if(serverName == null || serverName.isEmpty()){
    String message = "No Configuration found for resource. Please contact your administrator.";
    throw new BadRequestException(message);
}

Upvotes: 0

Related Questions