Custom exception message from google endpoints exception

400 views Asked by At

Currently, I've a Python endpoints service to change the name of a user. If there is no problem, I return a MessageField with a lot of informations.

But sometimes, the request is correct and I want to say to client that there is an error that he can handle : "Hey, sorry but there is already a user with this name", or also, "Hey, sorry but you have already change your name today !".

The problem is, when I raise an endpoint exception like a UnauthorizedException or anything else, I can just put a custom message :

raise endpoints.UnauthorizedException('Invalid user_id or auth_token !')

result in :

{
  "error": {
    "errors": [
      {
        "domain": "global",
        "reason": "required",
        "message": "Invalid user_id or auth_token !",
        "locationType": "header",
        "location": "Authorization"
      }
    ],
    "code": 401,
    "message": "Invalid user_id or auth_token !"
  }
}

Is there a way to really customize this message ? Or to return a completely different MessageField in this case ?

For example, I would like to return a JSON like this (maybe with HTTP Code 400) :

{
    "error": {
        "username_already_exist": 1
    }     
}

Thanks !

1

There are 1 answers

2
Patrice On

If you don't want to return the JSON that is build with an exception, you'll have to do a straight up return in your code instead of raising an exception. You can build the JSON you mention and then return that whenever you hit the "exception point".

Or what you can do is use the message to send the error to the client, then have the client catch that exception, parse appropriately, and display whatever you want.