def failed_request_exception(message, r):
    """Build ClickException from a failed request."""
    try:
        resp = json.loads(r.text)
        message = '%s: %d\n%s' % (message, resp['error']['code'],
                                  resp['error']['message'])
        return click.ClickException(message)
    except ValueError:
        # fallback on raw text response if error is not structured.
        return click.ClickException('%s: %d\n%s' % (message,
                                                    r.status_code,
                                                    r.text))
Build ClickException from a failed request.