# Tweepy
# Copyright 2009-2021 Joshua Roesslein
# See LICENSE for details.

import json


class TweepyException(Exception):
    """Base exception for Tweepy"""
    pass


class HTTPException(TweepyException):
    """Exception raised when an HTTP request fails"""

    def __init__(self, response):
        self.response = response

        self.api_errors = []
        self.api_codes = []
        self.api_messages = []

        try:
            response_json = response.json()
        except json.JSONDecodeError:
            super().__init__(f"{response.status_code} {response.reason}")
        else:
            error_text = []
            # Use := when support for Python 3.7 is dropped
            if "errors" not in response_json:
                super().__init__(f"{response.status_code} {response.reason}")
                return
            for error in response_json["errors"]:
                self.api_errors.append(error)
                if "code" in error:
                    self.api_codes.append(error["code"])
                if "message" in error:
                    self.api_messages.append(error["message"])
                if "code" in error and "message" in error:
                    error_text.append(f"{error['code']} - {error['message']}")
                elif "message" in error:
                    error_text.append(error["message"])
            error_text = '\n'.join(error_text)
            super().__init__(
                f"{response.status_code} {response.reason}\n{error_text}"
            )


class BadRequest(HTTPException):
    """Exception raised for a 400 HTTP status code"""
    pass


class Unauthorized(HTTPException):
    """Exception raised for a 401 HTTP status code"""
    pass


class Forbidden(HTTPException):
    """Exception raised for a 403 HTTP status code"""
    pass


class NotFound(HTTPException):
    """Exception raised for a 404 HTTP status code"""
    pass


class TooManyRequests(HTTPException):
    """Exception raised for a 429 HTTP status code"""
    pass


class TwitterServerError(HTTPException):
    """Exception raised for a 5xx HTTP status code"""

@@ -617,18 +617,43 @@
 rror
-_text =
+s = response_json.get(%22errors%22,
  %5B%5D
+)
 %0A   
@@ -734,14 +734,9 @@
 rror
-s%22 not
+%22
  in 
@@ -770,68 +770,44 @@
     
-super().__init__(f%22%7Bresponse.status_code%7D %7Bresponse.reason%7D%22
+errors.append(response_json%5B%22error%22%5D
 )%0A  
@@ -820,18 +820,23 @@
     
- 
-   return
+error_text = %22%22
 %0A   
@@ -861,31 +861,14 @@
  in 
-response_json%5B%22
 errors
-%22%5D
 :%0A  
@@ -1199,18 +1199,16 @@
 text
-.append(f%22
+ += f%22%5Cn
 %7Berr
@@ -1240,17 +1240,16 @@
 sage'%5D%7D%22
-)
 %0A       
@@ -1312,24 +1312,27 @@
 ror_text
-.append(
+ += '%5Cn' + 
 error%5B%22m
@@ -1343,56 +1343,8 @@
 ge%22%5D
-)%0A            error_text = '%5Cn'.join(error_text)
 %0A   
@@ -1428,18 +1428,16 @@
 .reason%7D
-%5Cn
 %7Berror_t

Handle "error" key in response JSON when initializing HTTPException