Parses a {@link Response} into an {@link ApiError}.

@param response the {@link Response} to parse.
@return an {@link ApiError} if parsable, or {@code null} if the response is not in error.
960318
@Nullable
    public static ApiError parseError(@Nonnull Response<?> response) {
        if (response.isSuccessful()) {
            return null;
        }

        try {
            return parseError(response.errorBody().string(), response.code(), response.message());
        } catch (IOException e) {
            return new ApiError(null, response.code(), "Unknown Error");
        }
    }
1107099
public static ModelAndView writeError(final HttpServletResponse response, final String error) {
        val model = CollectionUtils.wrap(OAuth20Constants.ERROR, error);
        val mv = new ModelAndView(new MappingJackson2JsonView(MAPPER), (Map) model);
        mv.setStatus(HttpStatus.BAD_REQUEST);
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        return mv;
    }
929777
public static String getResult(HttpResponse response) throws IOException {
		StringBuffer result = new StringBuffer();
		if (response.getEntity() != null && response.getEntity().getContent() != null) {
			BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			String line = "";
			while ((line = rd.readLine()) != null) {
				result.append(line);
			}
		}
		logger.info(result.toString());
		return result.toString();
	}
1117115
function (defer, response) {
                var error = response.error;
                if (error) {
                    defer.reject(new ApiError(error.type, error.message, error.data));
                } else {
                    defer.resolve(response.data);
                }
            }
530751
private static JSONObject genError(HttpResponse response) throws JSONException {
    	String code		= response.getFirstHeader("X-Upwork-Error-Code").getValue();
    	String message	= response.getFirstHeader("X-Upwork-Error-Message").getValue();
    	
    	if (code == null) {
    		code = Integer.toString(response.getStatusLine().getStatusCode());
    	}
    	
    	if (message == null) {
    		message = response.getStatusLine().toString();
    	}

    	return new JSONObject("{error: {code: \"" + code + "\", message: \"" + message + "\"}}");
    }
201694
protected HttpProxyResponse decodeResponse(final String response)
            throws Exception {
        LOGGER.debug("  parseResponse()");

        // Break response into lines
        String[] responseLines = response.split(HttpProxyConstants.CRLF);

        // Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
        // BUG FIX : Trimed to prevent failures with some proxies that add 
        // extra space chars like "Microsoft-IIS/5.0" ...
        String[] statusLine = responseLines[0].trim().split(" ", 2);

        if (statusLine.length < 2) {
            throw new Exception("Invalid response status line (" + statusLine
                    + "). Response: " + response);
        }

        // Status code is 3 digits
        if (statusLine[1].matches("^\\d\\d\\d")) {
            throw new Exception("Invalid response code (" + statusLine[1]
                    + "). Response: " + response);
        }

        Map<String, List<String>> headers = new HashMap<>();

        for (int i = 1; i < responseLines.length; i++) {
            String[] args = responseLines[i].split(":\\s?", 2);
            StringUtilities.addValueToHeader(headers, args[0], args[1], false);
        }

        return new HttpProxyResponse(statusLine[0], statusLine[1], headers);
    }
110925
@Override
    public T handleResponse(final HttpResponse response) throws IOException {

        InputStream content = null;
        final T addresses;

        try {
            final StatusLine status = response.getStatusLine();
            if (status.getStatusCode() >= HttpStatus.SC_BAD_REQUEST) {
                throw new IOException(String.format("HTTP error: %s %s", status.getStatusCode(), status.getReasonPhrase()));
            }
            content = response.getEntity().getContent();
            addresses = gsonInstance
                    .fromJson(new InputStreamReader(content, "utf-8"), responseType);
        } finally {
            if (null != content) {
                content.close();
            }
            response.getEntity().consumeContent();
        }

        return addresses;
    }
548280
public void generateError(String response) {
        final String errorInString = extractParameter(response, ERROR_REGEX_PATTERN, true);
        final String errorDescription = extractParameter(response, ERROR_DESCRIPTION_REGEX_PATTERN, false);
        final String errorUriInString = extractParameter(response, ERROR_URI_REGEX_PATTERN, false);
        URI errorUri;
        try {
            errorUri = errorUriInString == null ? null : URI.create(errorUriInString);
        } catch (IllegalArgumentException iae) {
            errorUri = null;
        }

        OAuth2Error errorCode;
        try {
            errorCode = OAuth2Error.parseFrom(errorInString);
        } catch (IllegalArgumentException iaE) {
            //non oauth standard error code
            errorCode = null;
        }

        throw new OAuth2AccessTokenErrorResponse(errorCode, errorDescription, errorUri, response);
    }
640008
function (error, response) {
        if (!_.isNull(error)) {
            error = _.createError(error);
        } else if (!_.isNull(response) && (response.status >= 400 || response.status === 0)) {
            error = _.createError(null, response);
            response = null;
        }
        callback(error, response);
    }
623199
private void parseResponse(HttpResponse response) throws MPException {
        this.statusCode = response.getStatusLine().getStatusCode();
        this.reasonPhrase = response.getStatusLine().getReasonPhrase();

        if (response.getEntity() != null) {
            HttpEntity respEntity = response.getEntity();
            try {
                this.stringResponse = MPCoreUtils.inputStreamToString(respEntity.getContent());
            } catch (Exception ex) {
                throw new MPException(ex);
            }

            // Try to parse the response to a json, and a extract the entity of the response.
            // When the response is not a json parseable string then the string response must be used.
            try {
                this.jsonElementResponse = new JsonParser().parse(this.stringResponse);

            } catch (JsonParseException jsonParseException) {
                // Do nothing
            }
        }
    }
934127
public void parseBatchResult(ClientResponse response) throws IOException,
            ServiceException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        InputStream inputStream = response.getEntityInputStream();
        ReaderWriter.writeTo(inputStream, byteArrayOutputStream);
        response.setEntityInputStream(new ByteArrayInputStream(
                byteArrayOutputStream.toByteArray()));
        JobInfo jobInfo;

        List<DataSource> parts = parseParts(response.getEntityInputStream(),
                response.getHeaders().getFirst("Content-Type"));

        if (parts.size() == 0 || parts.size() > entityBatchOperations.size()) {
            throw new UniformInterfaceException(String.format(
                    "Batch response from server does not contain the correct amount "
                            + "of parts (expecting %d, received %d instead)",
                    parts.size(), entityBatchOperations.size()), response);
        }

        for (int i = 0; i < parts.size(); i++) {
            DataSource ds = parts.get(i);
            EntityBatchOperation entityBatchOperation = entityBatchOperations
                    .get(i);

            StatusLine status = StatusLine.create(ds);
            InternetHeaders headers = parseHeaders(ds);
            InputStream content = parseEntity(ds);

            if (status.getStatus() >= HTTP_ERROR) {

                InBoundHeaders inBoundHeaders = new InBoundHeaders();
                @SuppressWarnings("unchecked")
                Enumeration<Header> e = headers.getAllHeaders();
                while (e.hasMoreElements()) {
                    Header header = e.nextElement();
                    inBoundHeaders.putSingle(header.getName(),
                            header.getValue());
                }

                ClientResponse clientResponse = new ClientResponse(
                        status.getStatus(), inBoundHeaders, content, null);

                UniformInterfaceException uniformInterfaceException = new UniformInterfaceException(
                        clientResponse);
                throw uniformInterfaceException;
            } else if (entityBatchOperation instanceof Job.CreateBatchOperation) {

                try {
                    jobInfo = oDataAtomUnmarshaller.unmarshalEntry(content,
                            JobInfo.class);
                    Job.CreateBatchOperation jobCreateBatchOperation = (Job.CreateBatchOperation) entityBatchOperation;
                    jobCreateBatchOperation.setJobInfo(jobInfo);
                } catch (JAXBException e) {
                    throw new ServiceException(e);
                }
            } else if (entityBatchOperation instanceof Task.CreateBatchOperation) {
                try {
                    oDataAtomUnmarshaller.unmarshalEntry(content,
                            TaskInfo.class);
                } catch (JAXBException e) {
                    throw new ServiceException(e);
                }
            }
        }
    }
998405
public static Tag outcome(ContainerResponse response) {
        if (response != null) {
            int status = response.getStatus();
            switch (Response.Status.Family.familyOf(status)) {
                case INFORMATIONAL:
                    return OUTCOME_INFORMATIONAL;

                case SUCCESSFUL:
                    return OUTCOME_SUCCESS;

                case REDIRECTION:
                    return OUTCOME_REDIRECTION;

                case CLIENT_ERROR:
                    return OUTCOME_CLIENT_ERROR;

                case SERVER_ERROR:
                    return OUTCOME_SERVER_ERROR;

                default:
                    return OUTCOME_UNKNOWN;
            }
        }
        /* In case there is no response we are dealing with an unmapped exception. */
        return OUTCOME_SERVER_ERROR;
    }
38873
function responseErrorBuilder(err, res) {
  if (res && res.body && _.isObject(res.body) && res.body.error) {
    // pass through error obj from API
    return res.body;
  } else {
    // build custom error
    return {
      error: {
        code: err.status || CL_CONSTANTS.RES_UNKNOWN,
        message: (res ? res.text : null) || err.toString(),
      }
    };
  }
}
321054
static public void captureReponseErrors(Object response, String errorMessage) throws Exception {
		if( null == response ) {
			throw new Exception("Capturing errors from null response");
		}
		if( false == (response instanceof JSONObject) ) {
			// Not an error
			return;
		}
		JSONObject obj = (JSONObject)response;
		if( JSONSupport.containsKey(obj,"error") ) {
			String serverMessage;
			try {
				serverMessage = obj.getString("error");
			} catch (Exception e) {
				serverMessage = "Unable to parse error response";
			}
			
			if( null == errorMessage ) {
				errorMessage = "Error returned by database: ";
			}
			throw new Exception(errorMessage+serverMessage);
		}
	}
412026
function parseResponse(response) {
    var code = response.statusCode;
    var type = code / 100 | 0;
    response.type = type;

    // basics
    switch (type) {
    case 1:
        response.info = type;
        break;
    case 2:
        response.ok = type;
        break;
    case 3:
        // ???
        break;
    case 4:
        response.clientError = type;
        response.error = type;
        response.ErrorClass = errors.HttpStatusError;
        break;
    case 5:
        response.serverError = type;
        response.error = type;
        response.ErrorClass = errors.HttpStatusError;
        break;
    }

    // error classes and sugar
    switch (code) {
    case 201:
        response.created = code;
        break;
    case 202:
        response.accepted = code;
        break;
    case 204:
        response.noContent = code;
        break;
    case 400:
        response.badRequest = code;
        break;
    case 401:
        response.unauthorized = code;
        response.ErrorClass = errors.AuthenticationRequiredError;
        break;
    case 403:
        response.forbidden = code;
        response.ErrorClass = errors.NotPermittedError;
        break;
    case 404:
        response.notFound = code;
        response.ErrorClass = errors.NotFoundError;
        break;
    case 406:
        response.notAcceptable = code;
        break;
    case 500:
        response.internalServerError = code;
        break;
    }

    // using body (and not status code)
    if (response.body && response.body.success === false) {
        if (!response.error) {
            response.error = 4; // assume is client error
            response.ErrorClass = errors.HttpStatusError;
        }
    }

    // null bodies
    if (_.includes([null, undefined, ""], response.body)) {
        if (!response.error) {
            response.error = 5; // assume the server fucked up
            response.ErrorClass = errors.HttpStatusError;
        }
    }

    return response;
}
470590
def parse_response(self, response):
        
        status = response.status_code
        if response.ok:
            data = response.json()
            return HttpResponse(ok=response.ok, status=status, errors=None, data=data)
        else:
            try:
                errors = response.json()
            except ValueError:
                errors = response.content
            return HttpResponse(ok=response.ok, status=status, errors=errors, data=None)
1045861
public void setResponse(InputStream response) {
		this.response = response;
		try {
			this.responseLength = response.available();
		} catch (IOException e) {
			// This shouldn't happen.
		}
	}