pythonamazon-web-serviceschalice

Chalice "BadRequestError is not JSON serializable" exception raised when returning a BadRequestError instance


Using the Chalice BadRequestResponse class for view exception handling is causing an exception stating the BadRequestResponse is not JSON serializable. Why is Chalice trying to cast the view output as JSON when the BadRequestResponse is returned from the view?

@auth.route('/auth/register', methods=['POST'])
def login():
    user_data = auth.current_request.json_body
    try:
        UserSchema().load(user_data)
        user = User(**user_data)
        user.save()
    except ValidationError as e:
        return BadRequestError("Why! This shouldn't be serialized to JSON!")
    else:
        return Response(status_code=201, body=user_data)

Solution

  • Whoops! I'm trying to return instead of raising the BadRequestError which is causing Chalice to cast the exception to JSON.