// ResponseError returns an empty Response with the ResponseError set from the
// given error.
4050
func ResponseError(err error) *Response {
	return &Response{ResponseError: err, BodyClosed: true, Response: &http.Response{}}
}
849022
func ResponderFromResponse(resp *http.Response) Responder {
	return func(req *http.Request) (*http.Response, error) {
		res := new(http.Response)
		*res = *resp
		res.Request = req
		return res, nil
	}
}
438193
func handleError(response *restful.Response, request string, err error) {
	switch err {
	case kubecontainer.ErrContainerNotFound:
		response.WriteError(http.StatusNotFound, err)
	default:
		msg := fmt.Sprintf("Internal Error: %v", err)
		klog.Errorf("HTTP InternalServerError serving %s: %s", request, msg)
		response.WriteErrorString(http.StatusInternalServerError, msg)
	}
}
701295
func handleError(URL string, resp *http.Response) error {
	errBytes, _ := ioutil.ReadAll(resp.Body)
	errInfo := string(errBytes)
	// Check if we have a JSON representation of the failure, if so decode it.
	if resp.Header.Get("Content-Type") == contentTypeJSON {
		var errResponse ErrorResponse
		if err := json.Unmarshal(errBytes, &errResponse); err == nil {
			errInfo = errResponse.Message
		}
	}
	httpError := &HttpError{
		resp.StatusCode, map[string][]string(resp.Header), URL, errInfo,
	}
	switch resp.StatusCode {
	case http.StatusBadRequest:
		return errors.NewBadRequestf(httpError, "", "Bad request %s", URL)
	case http.StatusUnauthorized:
		return errors.NewNotAuthorizedf(httpError, "", "Unauthorised URL %s", URL)
		//return errors.NewInvalidCredentialsf(httpError, "", "Unauthorised URL %s", URL)
	case http.StatusForbidden:
		//return errors.
	case http.StatusNotFound:
		return errors.NewResourceNotFoundf(httpError, "", "Resource not found %s", URL)
	case http.StatusMethodNotAllowed:
		//return errors.
	case http.StatusNotAcceptable:
		return errors.NewInvalidHeaderf(httpError, "", "Invalid Header %s", URL)
	case http.StatusConflict:
		return errors.NewMissingParameterf(httpError, "", "Missing parameters %s", URL)
		//return errors.NewInvalidArgumentf(httpError, "", "Invalid parameter %s", URL)
	case http.StatusRequestEntityTooLarge:
		return errors.NewRequestTooLargef(httpError, "", "Request too large %s", URL)
	case http.StatusUnsupportedMediaType:
		//return errors.
	case http.StatusServiceUnavailable:
		return errors.NewInternalErrorf(httpError, "", "Internal error %s", URL)
	case 420:
		// SlowDown
		return errors.NewRequestThrottledf(httpError, "", "Request throttled %s", URL)
	case 422:
		// Unprocessable Entity
		return errors.NewInvalidArgumentf(httpError, "", "Invalid parameters %s", URL)
	case 449:
		// RetryWith
		return errors.NewInvalidVersionf(httpError, "", "Invalid version %s", URL)
		//RequestMovedError -> ?
	}

	return errors.NewUnknownErrorf(httpError, "", "Unknown error %s", URL)
}
260242
func formatError(format string, err error) error {
	if s, ok := err.(errors.APIStatus); ok {
		se := &errors.StatusError{ErrStatus: s.Status()}
		se.ErrStatus.Message = fmt.Sprintf(format, se.ErrStatus.Message)
		return se
	}
	return fmt.Errorf(format, err)
}
1092372
func getError(r *http.Response, req *http.Request) error {
	if c := r.StatusCode; 200 <= c && c <= 299 {
		return nil
	}

	errorResponse := &ErrorResponse{Response: r}
	data, err := ioutil.ReadAll(r.Body)
	if err == nil && data != nil {
		json.Unmarshal(data, errorResponse)
	}
	errorResponse.Status = r.Status
	errorResponse.StatusCode = r.StatusCode
	errorResponse.Request = req

	switch r.StatusCode {
	case http.StatusBadRequest:
		return &ErrBadRequest{ErrorResponse: errorResponse}
	case http.StatusUnauthorized:
		return &ErrUnauthorized{ErrorResponse: errorResponse}
	case http.StatusServiceUnavailable:
		return &ErrTemporarilyUnavailable{ErrorResponse: errorResponse}
	case http.StatusNotFound:
		return &ErrNotFound{ErrorResponse: errorResponse}
	case http.StatusGone:
		return &ErrDeleted{ErrorResponse: errorResponse}
	default:
		return &ErrUnexpected{ErrorResponse: errorResponse}
	}
}
842421
func NewJiraError(resp *Response, httpError error) error {
	if resp == nil {
		return errors.Wrap(httpError, "No response returned")
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return errors.Wrap(err, httpError.Error())
	}
	jerr := Error{HTTPError: httpError}
	contentType := resp.Header.Get("Content-Type")
	if strings.HasPrefix(contentType, "application/json") {
		err = json.Unmarshal(body, &jerr)
		if err != nil {
			httpError = errors.Wrap(errors.New("Could not parse JSON"), httpError.Error())
			return errors.Wrap(err, httpError.Error())
		}
	} else {
        if httpError == nil {
            return fmt.Errorf("Got Response Status %s:%s", resp.Status, string(body))
        }
		return errors.Wrap(httpError, fmt.Sprintf("%s: %s", resp.Status, string(body)))
	}

	return &jerr
}
716874
func ResponseHeadersEncodeError(req *transport.Request, err error) error {
	return newServerEncodingError(req, nil, true /*isResponse*/, true /*isHeader*/, err)
}
373859
func RespondErrorCommon(req *Request, resp *Response, err error) (int, error) {
	if err == nil && (resp == nil || !resp.IsError()) {
		switch {
		case req.Operation == ReadOperation:
			if resp == nil {
				return http.StatusNotFound, nil
			}

		// Basically: if we have empty "keys" or no keys at all, 404. This
		// provides consistency with GET.
		case req.Operation == ListOperation && (resp == nil || resp.WrapInfo == nil):
			if resp == nil {
				return http.StatusNotFound, nil
			}
			if len(resp.Data) == 0 {
				if len(resp.Warnings) > 0 {
					return 0, nil
				}
				return http.StatusNotFound, nil
			}
			keysRaw, ok := resp.Data["keys"]
			if !ok || keysRaw == nil {
				// If we don't have keys but have other data, return as-is
				if len(resp.Data) > 0 || len(resp.Warnings) > 0 {
					return 0, nil
				}
				return http.StatusNotFound, nil
			}

			var keys []string
			switch keysRaw.(type) {
			case []interface{}:
				keys = make([]string, len(keysRaw.([]interface{})))
				for i, el := range keysRaw.([]interface{}) {
					s, ok := el.(string)
					if !ok {
						return http.StatusInternalServerError, nil
					}
					keys[i] = s
				}

			case []string:
				keys = keysRaw.([]string)
			default:
				return http.StatusInternalServerError, nil
			}

			if len(keys) == 0 {
				return http.StatusNotFound, nil
			}
		}

		return 0, nil
	}

	if errwrap.ContainsType(err, new(ReplicationCodedError)) {
		var allErrors error
		var codedErr *ReplicationCodedError
		errwrap.Walk(err, func(inErr error) {
			newErr, ok := inErr.(*ReplicationCodedError)
			if ok {
				codedErr = newErr
			} else {
				allErrors = multierror.Append(allErrors, inErr)
			}
		})
		if allErrors != nil {
			return codedErr.Code, multierror.Append(errors.New(fmt.Sprintf("errors from both primary and secondary; primary error was %v; secondary errors follow", codedErr.Msg)), allErrors)
		}
		return codedErr.Code, errors.New(codedErr.Msg)
	}

	// Start out with internal server error since in most of these cases there
	// won't be a response so this won't be overridden
	statusCode := http.StatusInternalServerError
	// If we actually have a response, start out with bad request
	if resp != nil {
		statusCode = http.StatusBadRequest
	}

	// Now, check the error itself; if it has a specific logical error, set the
	// appropriate code
	if err != nil {
		switch {
		case errwrap.ContainsType(err, new(StatusBadRequest)):
			statusCode = http.StatusBadRequest
		case errwrap.Contains(err, ErrPermissionDenied.Error()):
			statusCode = http.StatusForbidden
		case errwrap.Contains(err, ErrUnsupportedOperation.Error()):
			statusCode = http.StatusMethodNotAllowed
		case errwrap.Contains(err, ErrUnsupportedPath.Error()):
			statusCode = http.StatusNotFound
		case errwrap.Contains(err, ErrInvalidRequest.Error()):
			statusCode = http.StatusBadRequest
		case errwrap.Contains(err, ErrUpstreamRateLimited.Error()):
			statusCode = http.StatusBadGateway
		}
	}

	if resp != nil && resp.IsError() {
		err = fmt.Errorf("%s", resp.Data["error"].(string))
	}

	return statusCode, err
}
791666
func WriteErrorResponse(statusCode int, message string, w http.ResponseWriter) {
	var errstr []string

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(statusCode)
	errstr = append(errstr, http.StatusText(statusCode))
	resp := ErrorResponse{
		Status:  http.StatusText(statusCode),
		Message: message,
		Errors:  errstr,
	}
	json.NewEncoder(w).Encode(resp)
}
1069198
func getAPIError(code APIErrorCode) APIError {
	if apiErr, ok := errorCodes[code]; ok {
		return apiErr
	}
	return errorCodes.ToAPIErr(ErrInternalError)
}
295124
func HTTPError(w http.ResponseWriter, logMsg string, err string, errCode int) {
	if logMsg != "" {
		log.Println(logMsg)
	}

	http.Error(w, err, errCode)
}
594092
func (e ErrorResponse) Error() string {
	return fmt.Sprintf("API error %s %d (%s %d): %s", e.ErrorCode, e.ErrorCode, e.CSErrorCode, e.CSErrorCode, e.ErrorText)
}
382851
func DefaultErrorParser(resp *http.Response) error {
	resBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	rerr := new(Error)
	err = json.Unmarshal(resBody, rerr)
	if err != nil {
		return fmt.Errorf("invalid response body: %s", string(resBody))
	}
	if rerr.Title == "" {
		return fmt.Errorf("invalid response body: %s", string(resBody))
	} else {
		rerr.Status = resp.StatusCode
		return rerr
	}
}
133444
func RecoverError(resp *ResponseError) error {
	if resp == nil {
		return nil
	}
	switch resp.Code {
	case "invalid":
		return lease.ErrInvalid
	case "concurrent-update":
		return globalclock.ErrConcurrentUpdate
	default:
		return errors.New(resp.Message)
	}
}
66108
func getError(body []byte) error {
	var errResp ErrorResponse
	if err := json.Unmarshal(body, &errResp); err != nil {
		return err
	}
	return errResp.Error
}
537851
func replyError(c context.Context, rw http.ResponseWriter, code int, msg string, err error) {
	logging.WithError(err).Errorf(c, "HTTP %d: %s", code, msg)
	http.Error(rw, msg, code)
}