From 794696d327f5f9bc96d2703a4007b9f8bc3a1142 Mon Sep 17 00:00:00 2001 From: Mads Marquart Date: Tue, 2 Jul 2019 17:11:11 +0200 Subject: [PATCH] Improve payload error handling --- fbchat/_exception.py | 25 +++++++++++++++++++++++++ fbchat/_util.py | 35 ++++++++++++++++++++++++----------- 2 files changed, 49 insertions(+), 11 deletions(-) diff --git a/fbchat/_exception.py b/fbchat/_exception.py index c1dd0d6..8b28faf 100644 --- a/fbchat/_exception.py +++ b/fbchat/_exception.py @@ -28,5 +28,30 @@ class FBchatFacebookError(FBchatException): self.request_status_code = request_status_code +class FBchatInvalidParameters(FBchatFacebookError): + """Raised by Facebook if: + + - Some function supplied invalid parameters. + - Some content is not found. + - Some content is no longer available. + """ + + +class FBchatNotLoggedIn(FBchatFacebookError): + """Raised by Facebook if the client has been logged out.""" + + fb_error_code = "1357001" + + +class FBchatPleaseRefresh(FBchatFacebookError): + """Raised by Facebook if the client has been inactive for too long. + + This error usually happens after 1-2 days of inactivity. + """ + + fb_error_code = "1357004" + fb_error_message = "Please try closing and re-opening your browser window." + + class FBchatUserError(FBchatException): """Thrown by fbchat when wrong values are entered""" diff --git a/fbchat/_util.py b/fbchat/_util.py index c7b7eaf..c45dd39 100644 --- a/fbchat/_util.py +++ b/fbchat/_util.py @@ -11,7 +11,13 @@ from os.path import basename import warnings import logging import requests -from ._exception import FBchatException, FBchatFacebookError +from ._exception import ( + FBchatException, + FBchatFacebookError, + FBchatInvalidParameters, + FBchatNotLoggedIn, + FBchatPleaseRefresh, +) try: from urllib.parse import urlencode, parse_qs, urlparse @@ -118,17 +124,24 @@ def handle_error_in_payload(j): def handle_payload_error(j): - # TODO: Check known error codes, and raise more relevant errors! + if "error" not in j: + return + error = j["error"] + if j["error"] == 1357001: + error_cls = FBchatNotLoggedIn + elif j["error"] == 1357004: + error_cls = FBchatPleaseRefresh + elif j["error"] in (1357031, 1545010, 1545003): + error_cls = FBchatInvalidParameters + else: + error_cls = FBchatFacebookError # TODO: Use j["errorSummary"] - if "error" in j and "errorDescription" in j: - # "errorDescription" is in the users own language! - raise FBchatFacebookError( - "Error #{} when sending request: {}".format( - j["error"], j["errorDescription"] - ), - fb_error_code=j["error"], - fb_error_message=j["errorDescription"], - ) + # "errorDescription" is in the users own language! + raise error_cls( + "Error #{} when sending request: {}".format(error, j["errorDescription"]), + fb_error_code=error, + fb_error_message=j["errorDescription"], + ) def handle_graphql_error(j):