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 as shown in Example: error handling with WSThrows, in order to have them generated in the OpenAPI specification file and trapped on the client side.

However, you can code to trap a code number not defined in the WSThrows list with a call to the SetRestError() method. SetRestError() then returns the error code and optionally the error variable.

Example 2: managing unexpected errors

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,500:Internal Server Error")
  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