[SalesForce] Changing HTTP header code in POST response

I've been doing some research on this issue, but I haven't been able to find a solution. I'm trying to return HTTP 403 after failing to validate some information sent in a POST request to Salesforce. I have considered just throwing an exception to get some sort of error code returned, but that doesn't seem like a great way to do it.

I also tried using the HttpResponse class, but I'm not exactly sure how to. Doing something like the following yields the obvious error saying the function must return a String.

if (<some validation fails>) {
        HttpResponse err = new HttpResponse();
        err.setStatusCode(403);
        return err;
}

What's the best way to send a response with a specific HTTP header code through an Apex class?

Thanks!

EDIT

In response to @metadaddy, this is in an Apex class, ie:

@RestResource(urlMapping='/myendpoint')

global class MyClass {

    @HttpPost

    global static String doPost() {

        //Do stuff

        //Return something
        return JSON.serialize(retrievedVals);
    }
}

Best Answer

This pattern where you explicitly update the RestContext allows you to set the status value:

@HttpPost
global static void doPost() {

    // Do stuff

    RestResponse res = RestContext.response;
    if (res == null) {
        res = new RestResponse();
        RestContext.response = res;
    }

    // Return something
    res.responseBody = Blob.valueOf(JSON.serialize(retrievedVals));

    // Set the status
    res.statusCode = 403;
}

There is a more complete example here.

Related Topic