Open Source API Gateway

500 Internal Server Error: Error Serializing Map to JSON

Membrane API Gateway returns 500 Internal Server Error with the detail Error serializing Map to JSON when a javascript script returns a map that cannot be written as JSON. The script is part of the gateway configuration, so the configuration needs to be fixed.

The Error Response

The response contains the status 500 Internal Server Error, the detail Error serializing Map to JSON, the problem type https://membrane-api.io/problems/internal and a link to this page. In development mode, it also contains the error of the JSON serializer. The type internal means that the gateway could not complete the processing of the message. The status is 500 in the request and in the response flow. In production mode, the title is replaced by Internal Server Error and the details are left out.

How Script Results Become the Body

When a javascript script returns a map, Membrane writes the map as the JSON body of the message. For this to work, every value in the map must be convertible to JSON. See JavaScript plugin for more about scripts.

Common Causes

The Map Contains a Value That Cannot Be Serialized

The map contains an object that the JSON serializer cannot write, for example a Java or Groovy object without public getters. The serializer fails on such empty objects.

The Map Contains Circular References

The map contains itself, or objects that refer to each other in a cycle. Serializing them would never end, so the serializer fails.

How to Fix It

  1. Return only JSON-friendly values from the script: strings, numbers, booleans, null, and lists and maps of these.
  2. Convert other objects explicitly, for example with toString(), or copy the fields you need into a new map.
  3. To set a body in another format, return a string or a byte array, or a Response built in the script.
  4. Check the gateway log. The serializer error is logged at error level and names the value that failed.

Hide Details in Production

By default, Membrane runs in development mode and adds details to error responses that help you find the problem. These details may reveal information about your setup. In production, turn them off:

configuration:
production: true
configuration:
  production: true

Add the configuration document to your apis.yaml and separate it from the APIs with ---. The title then reads Internal Server Error, and the details and the link to this page are left out. If the response contains a log key, search the gateway log for it to find the full error message.

Related Documentation

Configuration reference:

Tutorials with runnable examples:

← All Membrane error messages

Still stuck? See the troubleshooting guide or ask on GitHub Issues. For commercial support, contact info@predic8.de.