Search code examples
anypoint-studiomulesoft

How to throw an error message if id field exist in POST request in Mulesoft 4


How to check if id in post request should not be included. I have 2 scenarios.

request body:

 {
    "name"="John"
 }

Expected result:

"Success"

request body:

 {
    "id"="323",
    "name"="Jane"
 }

Expected result: "id field should not be specified."


Solution

  • The following code will help you with what you are looking for

    %dw 1.0
    %output application/json
    ---
    {
        output: 'ID field should not be specified' 
        when payload.id? otherwise 'Success'
    }
    

    enter image description here

    enter image description here

    in mule 4: when otherwise has been replaced with if else. here is the dataweave code

    %dw 2.0
    output application/json
    ---
    
    if (payload.id?)
      { result: "ID field should not be specified" }
    else { result: "Success" }
    

    enter image description here