// mapErrorReason converts Apple error responses into exported Err variables
// for comparisons.
14076
func mapErrorReason(reason string) error {
	var e error
	switch reason {
	case "PayloadEmpty":
		e = ErrPayloadEmpty
	case "PayloadTooLarge":
		e = ErrPayloadTooLarge
	case "BadTopic":
		e = ErrBadTopic
	case "TopicDisallowed":
		e = ErrTopicDisallowed
	case "BadMessageId":
		e = ErrBadMessageID
	case "BadExpirationDate":
		e = ErrBadExpirationDate
	case "BadPriority":
		e = ErrBadPriority
	case "MissingDeviceToken":
		e = ErrMissingDeviceToken
	case "BadDeviceToken":
		e = ErrBadDeviceToken
	case "DeviceTokenNotForTopic":
		e = ErrDeviceTokenNotForTopic
	case "Unregistered":
		e = ErrUnregistered
	case "DuplicateHeaders":
		e = ErrDuplicateHeaders
	case "BadCertificateEnvironment":
		e = ErrBadCertificateEnvironment
	case "BadCertificate":
		e = ErrBadCertificate
	case "Forbidden":
		e = ErrForbidden
	case "BadPath":
		e = ErrBadPath
	case "MethodNotAllowed":
		e = ErrMethodNotAllowed
	case "TooManyRequests":
		e = ErrTooManyRequests
	case "IdleTimeout":
		e = ErrIdleTimeout
	case "Shutdown":
		e = ErrShutdown
	case "InternalServerError":
		e = ErrInternalServerError
	case "ServiceUnavailable":
		e = ErrServiceUnavailable
	case "MissingTopic":
		e = ErrMissingTopic
	default:
		e = errors.New(reason)
	}
	return e
}
1125511
func (g *Goon) KeyError(src interface{}) (*datastore.Key, error) {
	key, _, err := g.getStructKey(src)
	return key, err
}
886295
func handleError(
	err error) (*logical.Response, error) {
	if strings.Contains(err.Error(), logical.ErrReadOnly.Error()) {
		return logical.ErrorResponse(err.Error()), err
	}
	switch err.(type) {
	case logical.HTTPCodedError:
		return logical.ErrorResponse(err.Error()), err
	default:
		return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
	}
}
268507
func (defaultErrorHandler) HandleError(err error, w http.ResponseWriter, req *http.Request) {
	w.WriteHeader(http.StatusInternalServerError)
	fmt.Fprintf(w, "Error: %s", err)
}
43842
func ServerError(w http.ResponseWriter, r *http.Request, err error) {
	handlerMu.RLock()
	f, ok := handlerMap[http.StatusInternalServerError]
	handlerMu.RUnlock()
	if ok {
		r = ctxSetErr(r, err)
		f.ServeHTTP(w, r)
	} else {
		defaultServerError(w, r, err)
	}
}
1013249
func MakeError(data map[string]interface{}) SkygearError {
	err := SkygearError{}
	err.ID, _ = data["_id"].(string)
	err.Message, _ = data["message"].(string)
	if err.Message == "" {
		err.Message = "Unknown Error"
	}
	err.Code, _ = data["code"].(int)
	err.Type, _ = data["type"].(string)
	return err
}
1304051
func (ctx *Context) JSONError(v interface{}) error {
	ctx.Err500()
	return ctx.JSON(v)
}
446192
func ReplyErrorEncoder(
	ctx context.Context,
	err error,
	deliv *amqp.Delivery,
	ch Channel,
	pub *amqp.Publishing,
) {

	if pub.CorrelationId == "" {
		pub.CorrelationId = deliv.CorrelationId
	}

	replyExchange := getPublishExchange(ctx)
	replyTo := getPublishKey(ctx)
	if replyTo == "" {
		replyTo = deliv.ReplyTo
	}

	response := DefaultErrorResponse{err.Error()}

	b, err := json.Marshal(response)
	if err != nil {
		return
	}
	pub.Body = b

	ch.Publish(
		replyExchange,
		replyTo,
		false, // mandatory
		false, // immediate
		*pub,
	)
}
349131
func (es Errors) MarshalJSON() ([]byte, error) {
	errs := map[string]interface{}{}
	for key, err := range es {
		if ms, ok := err.(json.Marshaler); ok {
			errs[key] = ms
		} else {
			errs[key] = err.Error()
		}
	}
	return json.Marshal(errs)
}
823187
func (c *APIContext) ServerError(title string, err error) {
	c.Error(http.StatusInternalServerError, title, 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
}
1332434
func replyError(c context.Context, rw http.ResponseWriter, err error, msg string, args ...interface{}) {
	code := http.StatusBadRequest
	if transient.Tag.In(err) {
		code = http.StatusInternalServerError
	}
	msg = fmt.Sprintf(msg, args...)
	logging.Errorf(c, "HTTP %d: %s", code, msg)
	http.Error(rw, msg, code)
}
287975
func GetErrorPayload(serializer serialize.Serializer, err error) ([]byte, error) {
	code := e.ErrUnknownCode
	msg := err.Error()
	metadata := map[string]string{}
	if val, ok := err.(*e.Error); ok {
		code = val.Code
		metadata = val.Metadata
	}
	errPayload := &protos.Error{
		Code: code,
		Msg:  msg,
	}
	if len(metadata) > 0 {
		errPayload.Metadata = metadata
	}
	return SerializeOrRaw(serializer, errPayload)
}
329840
func DropReason(reason uint8) string {
	if err, ok := errors[reason]; ok {
		return err
	}
	return fmt.Sprintf("%d", reason)
}
1235601
func HTTPError(w http.ResponseWriter, code int) {
	msg := http.StatusText(code)
	Errorln(msg)
	m := make(map[string]string)
	m["status"] = "error"
	m["error"] = msg
	b, _ := json.MarshalIndent(m, "", "\t")
	http.Error(w, string(b), code)
}
700214
func (c *Client) FormatError(e ErrEntry) string {
	return fmt.Sprintf("%d %s [%s] %s request-%d retry-%d error: %s\n",
		e.Time.Unix(), e.Method, e.Verb, e.URL, e.Request, e.Retry, e.Err)
}
521804
func defaultErrorHandler(ctx *Context, data ...map[string]interface{}) {
	var renderData map[string]interface{}
	if len(data) == 0 {
		renderData = make(map[string]interface{})
		renderData["Code"] = ctx.statusCode
		renderData["Title"] = http.StatusText(ctx.statusCode)
		renderData["Message"] = http.StatusText(ctx.statusCode)
	} else {
		renderData = data[0]
	}
	if _, ok := renderData["Code"]; !ok {
		renderData["Code"] = ctx.statusCode
	}
	if _, ok := renderData["Title"]; !ok {
		renderData["Title"] = http.StatusText(ctx.statusCode)
	}
	if _, ok := renderData["Message"]; !ok {
		renderData["Message"] = http.StatusText(ctx.statusCode)
	}
	httpRequest, _ := httputil.DumpRequest(ctx.Request, true)
	renderData["HTTPRequest"] = string(httpRequest)
	var buf bytes.Buffer
	tmpl.Parse(errorTemplate)
	tmpl.Execute(&buf, renderData)
	ctx.Send(&buf)
}