1
+ import logging
2
+
3
+ import requests
4
+ from hearthsim .instrumentation .django_influxdb import write_point
1
5
from rest_framework import status
2
6
from rest_framework .exceptions import APIException
7
+ from rest_framework .views import exception_handler
3
8
4
9
5
10
class TwitchAPITimeout (APIException ):
@@ -20,3 +25,38 @@ class BadGateway(APIException):
20
25
class BadTwitchResponse (BadGateway ):
21
26
default_detail = "Twitch returned an invalid response."
22
27
default_code = "bad_twitch_response"
28
+
29
+
30
+ def untapped_django_exception_handler (exc , context ):
31
+ """A Django REST Framework "custom exception handler" for translating additional types.
32
+
33
+ This implementation attempts to convert upstream exception types corresponding to HTTP
34
+ 502 (Bad gateway) and HTTP 504 (Gateway timeout) before delegating to the default
35
+ exception handler implementation.
36
+
37
+ See also
38
+ https://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling
39
+
40
+ :param exc:
41
+ :param context:
42
+ """
43
+
44
+ if isinstance (exc , requests .Timeout ):
45
+ effective_exc = TwitchAPITimeout ()
46
+ elif (
47
+ isinstance (exc , requests .ConnectionError ) or
48
+ isinstance (exc , requests .HTTPError )
49
+ ):
50
+ effective_exc = BadGateway ()
51
+ else :
52
+ effective_exc = exc
53
+
54
+ detail = getattr (exc , "detail" , {})
55
+
56
+ logger = logging .getLogger ("twitch_hdt_ebs" )
57
+ logger .error ("Got exception %r, detail=%r" , exc , detail )
58
+
59
+ if detail and isinstance (detail , dict ):
60
+ write_point ("api_error" , {"count" : 1 }, error = detail .get ("error" , "unknown" ))
61
+
62
+ return exception_handler (effective_exc , context )
0 commit comments