2

I created an API that has error handling inside of it. However if the payload does not match what the API is expecting, the code inside the API does not execute. Thus it does not log an error to notify me that an incorrect payload was submitted.

How can I log this error inside SF or notify myself somehow, maybe by sending myself an email?

Here's an example of a response the API returned:

{
"message": "Expected List<String> but found "888" at [line:6, column:25]",
"errorCode": "JSON_PARSER_ERROR"
}
  • 1
    Are you using automatic deserialization, or are you parsing the JSON yourself? – sfdcfox Jan 8 '18 at 18:37
  • I believe I am using the automatic deserialization. Doing it manually should resolve my problem. Thanks for this! – Arthlete Jan 8 '18 at 18:55
6

If you do the deserialization/serialization in your own code you can catch and handle errors. You could also send yourself an email notification in that handling code.

In this pattern, the @RestResource method has no parameters and returns nothing and the code itself directly accesses the static RestContext.request and RestContext.response fields populated by the framework:

@HttpPost  
global static void post() {

    RestResponse res = RestContext.response;
    try {
        res.responseBody = Blob.valueOf(doPost());
        res.statusCode = 200;
    } catch (EndUserMessageException e) {
        // Use a specific exception type for expected conditions
        res.responseBody = Blob.valueOf(e.getMessage());
        res.statusCode = 400;
    } catch (Exception e) {
        // Unexpected conditions
        res.responseBody = Blob.valueOf(e.getMessage());
        res.statusCode = 500;
    }
}

private static String doPost() {

    String requestJson = RestContext.request.requestBody.toString();
    ...
    // Parse the request throwing an exception if the parse fails
    ...
    // Build the response and then serialize it to JSON
    ...
    return JSON.serialize(...);
}

See the RestContext Class and related documentation.

  • Thank you for this example. I had trouble finding this in the SF documentation! This is exactly what I wanted to do. – Arthlete Jan 8 '18 at 18:59
  • 1
    @Arthlete Yeah the docs emphasis serialization based on the method signature. This approach lets you handle various request and response formats in one class and, (if you are putting code in managed packages) avoids locking down the signature which is usually good (as its common that signatures change over time). – Keith C Jan 8 '18 at 19:01

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.