Example: handling expected application errors

Error handling is supported with the WSThrows and WSError attributes.

In your REST function expected errors, such as application level errors, are listed in the WSThrows attribute defined in the ATTRIBUTES clause of the function.

Example using WSError with WSThrows

In this example the expected error is for when a resource is not found so the HTTP status code "400" is listed in the WSThrows attribute. It also references the "userError" variable (@userError) defined with the WSError attribute for the description of the error at runtime.
Note: In the example, the variable is a record but you can define this as any suitable Genero BDL simple type.

You code to trap the error at runtime when a customer record is not found by updating the WSError attributed variable with a specific description of the HTTP status code, and calling the SetRestError() method to return it.

IMPORT com

PUBLIC DEFINE userError RECORD ATTRIBUTE(WSError="User error")
  message STRING
END RECORD

PUBLIC FUNCTION GetCustomersNameById( id STRING ATTRIBUTE(WSQuery) )
  ATTRIBUTES(WSGet,
             WSPath="/customers",
             WSThrows="400:@userError")
  RETURNS STRING
    DEFINE s STRING
    WHENEVER ERROR CONTINUE
      SELECT lname INTO s FROM customers WHERE @id  = id
    WHENEVER ERROR STOP
    IF SQLCA.SQLCODE == NOTFOUND THEN
        LET userError.message = SFMT("Could not find customer id :%1",id)
        CALL com.WebServiceEngine.SetRestError(400,userError)
    END IF
    RETURN s
END FUNCTION