How to Modify Backend Error Messages

In this recipe, you will learn how to dynamically change backend error responses to a custom format. We will use the standardized Problem JSON format for error responses.

Configuration

This configuration intercepts 4XX status codes and replaces them with a Problem JSON response.

<api port="2000">
  <response>             <!-- Regex for 4XX -->
    <if test="statusCode matches '4.*'" language="spel">
      <template contentType="application/json">
        {
          "type": "https://membrane-api.io/error/",
          "title": "${exc.response.statusMessage}",
          "status": ${exc.response.statusCode}
        }
      </template>
    </if>
  </response>
  <target url="localhost:2001" />
</api>

<api port="2001" name="mock server">
  <return statusCode="405" />
</api>

For more information on inline expressions and scripting in Membrane, see: Scripting.

Understanding the Configuration

Resources

If Documentation Examples
Template Documentation Examples