1- __version_info__ = ('3' , '6' , '5' )
2- __version__ = '.' .join (__version_info__ )
1+ import sys
2+
3+ from six import u
4+
5+ # Backwards compatibility.
6+ from .version import __version__ , __version_info__
37
48
59class TwilioException (Exception ):
@@ -12,17 +16,57 @@ class TwilioRestException(TwilioException):
1216 :param int status: the HTTP status that was returned for the exception
1317 :param str uri: The URI that caused the exception
1418 :param str msg: A human-readable message for the error
19+ :param str method: The HTTP method used to make the request
1520 :param int|None code: A Twilio-specific error code for the error. This is
1621 not available for all errors.
1722 """
1823
1924 # XXX: Move this to the twilio.rest folder
2025
21- def __init__ (self , status , uri , msg = "" , code = None ):
26+ def __init__ (self , status , uri , msg = "" , code = None , method = 'GET' ):
2227 self .uri = uri
2328 self .status = status
2429 self .msg = msg
2530 self .code = code
31+ self .method = method
2632
2733 def __str__ (self ):
28- return "HTTP ERROR %s: %s \n %s" % (self .status , self .msg , self .uri )
34+ """ Try to pretty-print the exception, if this is going on screen. """
35+
36+ def red (words ):
37+ return u ("\033 [31m\033 [49m%s\033 [0m" ) % words
38+
39+ def white (words ):
40+ return u ("\033 [37m\033 [49m%s\033 [0m" ) % words
41+
42+ def blue (words ):
43+ return u ("\033 [34m\033 [49m%s\033 [0m" ) % words
44+
45+ def teal (words ):
46+ return u ("\033 [36m\033 [49m%s\033 [0m" ) % words
47+
48+ def get_uri (code ):
49+ return "https://www.twilio.com/docs/errors/{}" .format (code )
50+
51+ # If it makes sense to print a human readable error message, try to
52+ # do it. The one problem is that someone might catch this error and
53+ # try to display the message from it to an end user.
54+ if hasattr (sys .stderr , 'isatty' ) and sys .stderr .isatty ():
55+ msg = (
56+ "\n {red_error} {request_was}\n \n {http_line}"
57+ "\n \n {twilio_returned}\n \n {message}\n " .format (
58+ red_error = red ("HTTP Error" ),
59+ request_was = white ("Your request was:" ),
60+ http_line = teal ("%s %s" % (self .method , self .uri )),
61+ twilio_returned = white (
62+ "Twilio returned the following information:" ),
63+ message = blue (str (self .msg ))
64+ ))
65+ if self .code :
66+ msg = "" .join ([msg , "\n {more_info}\n \n {uri}\n \n " .format (
67+ more_info = white ("More information may be available here:" ),
68+ uri = blue (get_uri (self .code ))),
69+ ])
70+ return msg
71+ else :
72+ return "HTTP {} error: {}" .format (self .status , self .msg )
0 commit comments