0

I have an Item object in Org2 that I can post from Org1 (in Org1 is Tool object that passes its fields to THIS (Item) object). Item has ExternalID field that takes the ID from Tool. How can I send an error to Callout if Item with this ExternalID is already posted?

@HttpPost
global static Item__c post() {
    RestRequest req = RestContext.request;          
    Item__c item = new Item__c();
    //Here we get our Item record with ExternalID already:
    String body = req.requestBody.toString();
    RestResponse res = new RestResponse();
    RestContext.response = res;

    try{
        it = (Item__c)JSON.deserialize(body, Item__c.class);
        insert item;
        res.responseBody = Blob.valueOf(JSON.serialize(item));
        res.statusCode = 200;
        return item;
    } catch(Exception e) {
        res.statusCode = 500;
    } 
    return null;
}
3

you can do SOQL query on Item__c filtering by ExternalID__c field. If result is not empty, then set statusCode to relevant one. You can find list of all status codes here.


do not set RestContext.response.responseBody and use return at same time, as return result will be set as response body.

  • If the method returns void, then Apex REST returns the response in the responseBody property.
  • If the method returns a value, then Apex REST serializes the return value as the response.

also I suggest you to set some message in body, if such external Id already exists

@HttpPost
global static void post() {
    RestRequest req = RestContext.Request;          
    String body = req.requestBody.toString();
    Item__c item = (Item__c)JSON.deserialize(body, Item__c.class);
    RestResponse response = new RestResponse();
    if([
        select Id
        from Item__c
        where ExternalID__c = :item.ExternalID__c
        limit 1
    ].isEmpty()){
        insert item;
        response.statusCode = 200;
        response.responseBody = Blob.valueOf(JSON.serialize(item));
    }else{
        response.statusCode = 409; // CONFLICT status code
        response.responseBody = Blob.valueOf('Item with External Id ' + item.ExternalID__c + 'already exists');
    }
    RestContext.response = response;
}
  • I don't know why, but this thing can't back error msg. If I do with try/catch - no probs with that. On another side I use throw new MeException for errors on VF page. Maybe because of that? And I get there statuscode 200 anyway – MichaelLev19 Oct 29 '18 at 8:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.