Better error message when missing required fields from request

2.7k Views Asked by At

When missing a required field currently ProtoRPC returns a message like this:

{
 "error": {
  "code": 400, 
  "errors": [
   {
    "domain": "global", 
    "message": "Error parsing ProtoRPC request (Unable to parse request content: Message CombinedContainer is missing required field api_key)", 
    "reason": "badRequest"
   }
  ], 
  "message": "Error parsing ProtoRPC request (Unable to parse request content: Message CombinedContainer is missing required field api_key)"
 }
}

Is it possible to provide a better error message? Ideally, "missing required field api_key" in this example.

According to the Google Code Issue Tracker and Github issues this was once being worked on. However, there does not appear to be any activity.

I'd greatly appreciate any solutions or workarounds.

1

There are 1 best solutions below

0
On

As of today, the ProtoRPC still returns the same unraised error which makes it harder for one to return a customized error response.

A simple workaround is to make the Message fields optional and enforce the requirement constraint somewhere in the endpoint handler/method.

So instead of;

class Request(Message):
    name = StringField(1, required=True)

Set 'name' as optional,

class Request(Message):
    name = StringField(1)

The requirement constraint can then be enforced in the endpoint handler method by simple if statements OR by mapping these fields to a Datastore entity that requires these fields, hence will allow exception handling of BadValueError and return a more customized error response.

Example:

try:
    account = Account(name=request.name)
    account.put()
except BadValueError:
    return Response(status=False, message='Missing field "name"')