Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Cloud Function responds Internal Server Error on invalid JSON data in Post request

Observed behaviour: Nodejs Cloud Functions will respond with an Internal Server Error, if the POST request has Content-Type: application/json and the request body is not a valid JSON Object. The http handler is not executed. The logs say 'SyntaxError: ... at JSON.parse'.

Desired behaviour: The http handler should be executed. This is equivalent to the behaviour of Python Cloud Functions.

Is there a way to achieve the desired behaviour? Or is this maybe even a bug in Cloud Functions?

Solved Solved
0 2 218
1 ACCEPTED SOLUTION

The issue has been fixed in version 3.4.6 of the functions framework. The function will now respond with a 400 Error instead.

 

View solution in original post

2 REPLIES 2

Hi @Lionel_Damtew,

Welcome to the Google Cloud community!

You can manage this situation by handling the error within your function and ensuring the handler is executed even if the request body is invalid. You can do this by directly checking for valid JSON before attempting to parse it.

This approach allows your Cloud Function to continue executing even if the request body is not a valid JSON object, and it avoids the automatic error caused by the JSON parsing failure.

  • Express Middleware: The middleware express.json() is used to parse the JSON body of the request. If the body is invalid, it doesn't throw an error directly but adds a custom flag (req.invalidJson).
  • Error Handling: In your route handler, check whether the body was valid JSON by checking the req.invalidJson flag. If the flag is set, you can send a 400 Bad Request response with a message indicating the body is invalid JSON. Otherwise, you process the request normally.

For more in-depth analysis, you can contact Google Cloud Support. When contacting them, please provide comprehensive details and include screenshots. This will help them better understand and address your issue.

Was this helpful? If so, please accept this answer as “Solution”. If you need additional assistance, reply here within 2 business days and I’ll be happy to help.

The issue has been fixed in version 3.4.6 of the functions framework. The function will now respond with a 400 Error instead.