3

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);
    }
}
2
  • Is this in an Apex REST Method or a Visualforce Page?
    – metadaddy
    Commented Dec 10, 2014 at 6:49
  • @metadaddy this is in an Apex REST method - see my edit please.
    – rebello95
    Commented Dec 10, 2014 at 6:55

1 Answer 1

3

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.

1
  • Awesome! This is exactly what I needed, thank you!
    – rebello95
    Commented Dec 10, 2014 at 15:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .