// RenderErrorJSON is a gin middleware to render error in json format
961625
func RenderErrorJSON(c *gin.Context) {
	c.Next()

	if len(c.Errors) > 0 {
		errs := []error{}
		for _, err := range c.Errors {
			errs = append(errs, err)
		}

		c.JSON(
			http.StatusNotFound,
			errutil.NewErrors(errs...),
		)
	}
}
514200
func (r *RenderTemplateResult) renderError(err error, req *Request, resp *Response) {
	compileError, found := err.(*Error)
	if !found {
		var templateContent []string
		templateName, line, description := ParseTemplateError(err)
		if templateName == "" {
			templateLog.Info("Cannot determine template name to render error", "error", err)
			templateName = r.Template.Name()
			templateContent = r.Template.Content()

		} else {
			lang, _ := r.ViewArgs[CurrentLocaleViewArg].(string)
			if tmpl, err := MainTemplateLoader.TemplateLang(templateName, lang); err == nil {
				templateContent = tmpl.Content()
			} else {
				templateLog.Info("Unable to retreive template ", "error", err)
			}
		}
		compileError = &Error{
			Title:       "Template Execution Error",
			Path:        templateName,
			Description: description,
			Line:        line,
			SourceLines: templateContent,
		}
	}
	resp.Status = 500
	resultsLog.Errorf("render: Template Execution Error (in %s): %s", compileError.Path, compileError.Description)
	ErrorResult{r.ViewArgs, compileError}.Apply(req, resp)
}
1246770
func ErrorToJSONAPIError(ctx context.Context, err error) (app.JSONAPIError, int) {
	cause := errs.Cause(err)
	detail := cause.Error()
	var title, code string
	var statusCode int
	var id *string
	log.Error(ctx, map[string]interface{}{"err": cause, "error_message": cause.Error(), "err_type": reflect.TypeOf(cause)}, "an error occurred in our api")
	switch cause.(type) {
	case errors.NotFoundError:
		code = ErrorCodeNotFound
		title = "Not found error"
		statusCode = http.StatusNotFound
	case errors.ConversionError:
		code = ErrorCodeConversionError
		title = "Conversion error"
		statusCode = http.StatusBadRequest
	case errors.BadParameterError:
		code = ErrorCodeBadParameter
		title = "Bad parameter error"
		statusCode = http.StatusBadRequest
	case errors.VersionConflictError:
		code = ErrorCodeVersionConflict
		title = "Version conflict error"
		statusCode = http.StatusConflict
	case errors.DataConflictError:
		code = ErrorCodeDataConflict
		title = "Data conflict error"
		statusCode = http.StatusConflict
	case errors.InternalError:
		code = ErrorCodeInternalError
		title = "Internal error"
		statusCode = http.StatusInternalServerError
	case errors.UnauthorizedError:
		code = ErrorCodeUnauthorizedError
		title = "Unauthorized error"
		statusCode = http.StatusUnauthorized
	case errors.ForbiddenError:
		code = ErrorCodeForbiddenError
		title = "Forbidden error"
		statusCode = http.StatusForbidden
	default:
		code = ErrorCodeUnknownError
		title = "Unknown error"
		statusCode = http.StatusInternalServerError

		cause := errs.Cause(err)
		if err, ok := cause.(goa.ServiceError); ok {
			statusCode = err.ResponseStatus()
			idStr := err.Token()
			id = &idStr
			title = http.StatusText(statusCode)
		}
		if errResp, ok := cause.(*goa.ErrorResponse); ok {
			code = errResp.Code
			detail = errResp.Detail
		}
	}
	statusCodeStr := strconv.Itoa(statusCode)
	jerr := app.JSONAPIError{
		ID:     id,
		Code:   &code,
		Status: &statusCodeStr,
		Title:  &title,
		Detail: detail,
	}
	return jerr, statusCode
}
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)
}
612891
func (j JE) Render() map[string]string {

	if j.error == "" {
		if j.message == "" {
			return map[string]string{"code": fmt.Sprintf("%d", j.Code)}
		} else {
			return map[string]string{"code": fmt.Sprintf("%d", j.Code), "message": j.message}
		}
	} else {
		if j.message == "" {
			return map[string]string{"code": fmt.Sprintf("%d", j.Code), "error": j.error}
		} else {
			return map[string]string{"code": fmt.Sprintf("%d", j.Code), "error": j.error, "message": j.message}
		}
	}
}
1116915
func (api *API) RespondError(err error) error {
	var response errorResponse
	response.Error = err.Error()

	return sendSerializedJSONMessage(response, api.Writer)
}
517043
func (e *Error) MarshalJSON() (result []byte, err error) {
	ee := errEncode{
		Code: e.Code,
		Msg:  e.Msg,
		Op:   e.Op,
	}
	if e.Err != nil {
		if _, ok := e.Err.(*Error); ok {
			_, err := e.Err.(*Error).MarshalJSON()
			if err != nil {
				return result, err
			}
			ee.Err = e.Err
		} else {
			ee.Err = e.Err.Error()
		}
	}
	return json.Marshal(ee)
}
465170
func httpError(status int, format string, a ...interface{}) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, fmt.Sprintf(format, a...), http.StatusInternalServerError)
	})
}
209473
func (e *presentableError) render(c *router.Context) {
	breadcrumps := []string{}
	for _, k := range []string{"ProjectID", "JobName", "InvID"} {
		p := c.Params.ByName(k)
		if p == "" {
			break
		}
		breadcrumps = append(breadcrumps, p)
	}
	c.Writer.Header().Set("Content-Type", "text/html; charset=utf-8")
	c.Writer.WriteHeader(e.Status)
	templates.MustRender(c.Context, c.Writer, "pages/error.html", map[string]interface{}{
		"Breadcrumps":    breadcrumps,
		"LastCrumbIdx":   len(breadcrumps) - 1,
		"Message":        e.Message,
		"ReloginMayHelp": e.ReloginMayHelp,
	})
}
351294
func MarshalErrors(w io.Writer, errorObjects []*ErrorObject) error {
	return json.NewEncoder(w).Encode(&ErrorsPayload{Errors: errorObjects})
}
584795
func renderErr(c *router.Context, err error) {
	status := grpcCodeToHTTP[grpc.Code(err)]
	if status == 0 {
		status = http.StatusInternalServerError
	}
	c.Writer.Header().Set("Content-Type", "text/html; charset=utf-8")
	c.Writer.WriteHeader(status)
	templates.MustRender(c.Context, c.Writer, "pages/error.html", map[string]interface{}{
		"Message": err.Error(),
	})
}
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)
}
94275
func (t *Template) RenderString(context ...interface{}) (string, error) {
	b := &bytes.Buffer{}
	err := t.Render(b, context...)
	return b.String(), err
}
682192
func (r Response) FormatError() error {
	if len(r.body) == 0 {
		return fmt.Errorf("Error: %v", r.err)
	}
	return fmt.Errorf("%v", strings.TrimSpace(string(r.body)))
}
437969
func (h *JSONWriter) WriteErrorCode(w http.ResponseWriter, r *http.Request, code int, err interface{}) {
	if err == nil {
		err = toError(err)
	}

	if code == 0 {
		code = http.StatusInternalServerError
	}

	// All errors land here, so it's a really good idea to do the logging here as well!
	h.Reporter(h.logger, "An error occurred while handling a request")(w, r, code, toError(err))

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(code)

	// Enhancing must happen after logging or context will be lost.
	if h.ErrorEnhancer != nil {
		err = h.ErrorEnhancer(r, toError(err))
	}

	if err := json.NewEncoder(w).Encode(err); err != nil {
		// There was an error, but there's actually not a lot we can do except log that this happened.
		h.Reporter(h.logger, "Could not write jsonError to response writer")(w, r, code, errors.WithStack(err))
	}
}
416333
func (j JSON) Render(w io.Writer, v interface{}) error {
	if j.StreamingJSON {
		return j.renderStreamingJSON(w, v)
	}

	var result []byte
	var err error

	if j.Indent {
		result, err = json.MarshalIndent(v, "", "  ")
		result = append(result, '\n')
	} else {
		result, err = json.Marshal(v)
	}
	if err != nil {
		return err
	}

	// Unescape HTML if needed.
	if j.UnEscapeHTML {
		result = bytes.Replace(result, []byte("\\u003c"), []byte("<"), -1)
		result = bytes.Replace(result, []byte("\\u003e"), []byte(">"), -1)
		result = bytes.Replace(result, []byte("\\u0026"), []byte("&"), -1)
	}

	// JSON marshaled fine, write out the result.
	if hw, ok := w.(http.ResponseWriter); ok {
		j.Head.Write(hw)
	}
	if len(j.Prefix) > 0 {
		w.Write(j.Prefix)
	}
	w.Write(result)
	return nil
}
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)
	}
}