WebAPI JSON Message Body Validation with TRY Method

Hi Appian Community,

I want to implement a simple Try... Catch within my Web API sail expression to test the request body being a valid JSON message. I still notice that the Try() function is not publicized in the documentation but it has been an easier implementation. And in posts that mention Try() function it heavily cautions that it is not recommended and could become unavailable.

I looked into using some regular expressions off Google that match for JSON as an alternative but found they aren't compliant with the regex plugin.

Example Regex

/(?<o>{((?<s>\"([^\0-\x1F\"\\]|\\[\"\\\/bfnrt]|\\u[0-9a-fA-F]{4})*\"):(?<v>\g<s>|(?<n>-?(0|[1-9]\d*)(.\d+)?([eE][+-]?\d+)?)|\g<o>|\g<a>|true|false|null))?\s*((?<c>,\s*)\g<s>(?<d>:\s*)\g<v>)*})|(?<a>\[\g<v>?(\g<c>\g<v>)*\])/

What are some recommended HTTP Request Body validation expressions that can validate whether the message is JSON or XML? It would be great if WebAPI object can handle the content-type validation automatically for us.

Below code is using try() function to test fromJson works or not with the HTTP request body.

a!localVariables(
  local!jsonTest: try(
    a!fromJson(http!request.body),
    "JSON_PARSE_ERROR"
  ),
  if(
    tostring(local!jsonTest)="JSON_PARSE_ERROR",
    a!httpResponse(
      statusCode:400,
      headers: {
        a!httpHeader(
          name: "Content-Type",
          value: "application/json"
        )
      },
      body:a!toJson(
        {
          error:400,
          errorMessage:"Request body could not be read as JSON object."
        }
      )
    ),
    a!startProcess(
      processModel: cons!SOME_PROCESS_MODEL,
      processParameters: a!map(rawTextDataInput: http!request.body),
      onSuccess: a!httpResponse(
        statusCode: 200,
        headers: {
          a!httpHeader(
            name: "Content-Type",
            value: "application/json"
          )
        },
        body: a!toJson(fv!processInfo)
      ),
      onError: a!httpResponse(
        statusCode: 500,
        headers: {
          a!httpHeader(
            name: "Content-Type",
            value: "application/json"
          )
        },
        body: a!toJson(
          {
            error: "There was an error starting the process"
          }
        )
      )
    )
  )

)

  Discussion posts and replies are publicly visible