1111 */
1212class ResponseError
1313{
14+ const EXCEPTION_MESSAGE = 'Got error response from the server: %s ' ;
1415
1516 const SUCCESS = 1 ;
1617
@@ -25,34 +26,34 @@ class ResponseError
2526
2627 const CHAT_API_AUTH_ERROR = 1001 ;
2728
28- public $ errors = array ();
29+ public $ errors = array ();
2930
3031 /**
3132 * Load the error data into an array.
3233 * Throw an exception when important errors are found.
3334 *
3435 * @param $body
3536 *
36- * @throws Exceptions\BalanceException
3737 * @throws Exceptions\AuthenticateException
38+ * @throws Exceptions\BalanceException
3839 */
3940 public function __construct ($ body )
4041 {
4142 if (!empty ($ body ->errors )) {
4243 foreach ($ body ->errors AS $ error ) {
44+ // Voice API returns errors with a "message" field instead of "description".
45+ // This ensures all errors have a description set.
46+ if (!empty ($ error ->message )) {
47+ $ error ->description = $ error ->message ;
48+ unset($ error ->message );
49+ }
4350
4451 if ($ error ->code === self ::NOT_ENOUGH_CREDIT ) {
45- throw new Exceptions \BalanceException ;
52+ throw new Exceptions \BalanceException ( $ this -> getExceptionMessage ( $ error )) ;
4653 } elseif ($ error ->code === self ::REQUEST_NOT_ALLOWED ) {
47- throw new Exceptions \AuthenticateException ;
54+ throw new Exceptions \AuthenticateException ( $ this -> getExceptionMessage ( $ error )) ;
4855 } elseif ($ error ->code === self ::CHAT_API_AUTH_ERROR ) {
49- throw new Exceptions \AuthenticateException ;
50- }
51-
52- // Rewrite error for Voice API.
53- if (!empty ($ error ->message )) {
54- $ error ->description = $ error ->message ;
55- unset($ error ->message );
56+ throw new Exceptions \AuthenticateException ($ this ->getExceptionMessage ($ error ));
5657 }
5758
5859 $ this ->errors [] = $ error ;
@@ -61,17 +62,30 @@ public function __construct($body)
6162 }
6263
6364 /**
64- * Get the error string to show in the Exception message.
65+ * Get the exception message for the provided error.
66+ *
67+ * @param $error
68+ *
69+ * @return string
70+ */
71+ private function getExceptionMessage ($ error )
72+ {
73+ return sprintf (self ::EXCEPTION_MESSAGE , $ error ->description );
74+ }
75+
76+ /**
77+ * Get a string of all of this response's concatenated error descriptions.
6578 *
6679 * @return string
6780 */
6881 public function getErrorString ()
6982 {
70- $ errorString = array ();
83+ $ errorDescriptions = array ();
84+
7185 foreach ($ this ->errors AS $ error ) {
72- $ errorString [] = $ error ->description ;
86+ $ errorDescriptions [] = $ error ->description ;
7387 }
7488
75- return implode (', ' , $ errorString );
89+ return implode (', ' , $ errorDescriptions );
7690 }
7791}
0 commit comments