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>
<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

  • <if>: Evaluates whether the response has a 4XX error code.
  • <template>: Generates a JSON-formatted response replacing the original error message.
  • ${exc.response.statusMessage}: Extracts the original error message.
  • ${exc.response.statusCode}: Retrieves the status code from the response.

Resources

ElementDocsExamples
IfDocumentationExamples
TemplateDocumentationExamples