Example: handling an unexpected error

Example of a method you can use to code for unexpected errors.

Warning: In general, the recommended option is to list all the possible errors in order to have them generated in the OpenAPI specification file and trapped on the client side.

Not all errors can be anticipated. In this case, an unexpected error can be handled in your REST function. Unexpected error are the ones not listed in the WSThrows attribute.

Example: managing unexpected errors

In this example, an expected error is listed in the WSThrows attribute. In the code, the OTHERWISE clause traps an error which is not listed in the WSThrows attribute.

The call to the SetRestError() method returns the HTTP status code to the client. The error description is set to NULL, which allows the HTTP standard error description to be returned, but you could also return a description in this case; optionally using the variable defined with the WSError attribute.
IMPORT com

TYPE accountType RECORD ... END RECORD

PUBLIC DEFINE myError RECORD ATTRIBUTE(WSError="user error")
  message STRING
END RECORD

PUBLIC FUNCTION queryAccountsById( id VARCHAR(10) ATTRIBUTE(WSParam) )
  ATTRIBUTES(WSGet,
             WSPath="/accounts/{id}",
             WSThrows="400:@myError")
  RETURNS accountType ATTRIBUTES(WSName="body")
    DEFINE thisAccount accountType
    WHENEVER ERROR CONTINUE
    SELECT * INTO thisAccount.* FROM accounts WHERE @id  = id
    WHENEVER ERROR STOP
    CASE
    WHEN SQLCA.SQLCODE = 0
        EXIT CASE
    WHEN SQLCA.SQLCODE = NOTFOUND
        LET myError.message = SFMT("Could not find account id :%1",id)
        CALL com.WebServiceEngine.SetRestError(400,myError)
    OTHERWISE
       CALL com.WebServiceEngine.SetRestError(505,NULL)
    END CASE
    RETURN thisAccount.*
END FUNCTION