olucurious/PyFCM

The InvalidDataError exception logs multi line text (JSON)

c4talyst opened this issue · 1 comments

Summary

The InvalidDataError Exception, when logged, outputs multi-line text (which happens to also be JSON) which is not properly handled by things like Google Cloud Log Explorer. This makes filtering logs difficult.

raise InvalidDataError(response.text)

Resolution

  • Remove newlines from response.text.
  • (Or) Detect that the content is JSON and un-pretty-print it.

Steps to reproduce

Using pyfcm==2.0.4

from pyfcm import FCMNotification
push_service = FCMNotification(
    service_account_file="local_creds.json",
    project_id="xxx",
)

result = push_service.notify(
    fcm_token="cheeseburgers",
    notification_title=title,
    notification_body=message_body,
)
Traceback (most recent call last):
  File "/home/dan/xxx/dan-test.py", line 64, in <module>
    result = push_service.notify(
  File "/home/dan/xxx/venv/lib/python3.10/site-packages/pyfcm/fcm.py", line 67, in notify
    return self.parse_response(response)
  File "/home/dan/xxx/venv/lib/python3.10/site-packages/pyfcm/baseapi.py", line 212, in parse_response
    raise InvalidDataError(response.text)
pyfcm.errors.InvalidDataError: {
  "error": {
    "code": 400,
    "message": "The registration token is not a valid FCM registration token",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.firebase.fcm.v1.FcmError",
        "errorCode": "INVALID_ARGUMENT"
      }
    ]
  }
}

My wordaround for now:

try:
    result = push_service.notify(
        fcm_token="cheeseburgers",
        notification_title=title,
        notification_body=message_body,
)
except InvalidDataError as e:
    error_message = str(e)
    # Remove newlines and extra spaces
    formatted_error_message = ' '.join(error_message.split())
    raise InvalidDataError(formatted_error_message) from None