Grafana: Replace magic number with a constant variable in response status (#80132)

* Chore: Replace response status with const var

* Apply suggestions from code review

Co-authored-by: Sofia Papagiannaki <1632407+papagian@users.noreply.github.com>

* Add net/http import

---------

Co-authored-by: Sofia Papagiannaki <1632407+papagian@users.noreply.github.com>
This commit is contained in:
김은빈 2024-02-28 01:39:51 +09:00 committed by GitHub
parent a7fbe3c6dc
commit 96dfb385ca
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
36 changed files with 260 additions and 255 deletions

View File

@ -62,12 +62,12 @@ func (hs *HTTPServer) AdminGetVerboseSettings(c *contextmodel.ReqContext) respon
func (hs *HTTPServer) AdminGetStats(c *contextmodel.ReqContext) response.Response {
adminStats, err := hs.statsService.GetAdminStats(c.Req.Context(), &stats.GetAdminStatsQuery{})
if err != nil {
return response.Error(500, "Failed to get admin stats from database", err)
return response.Error(http.StatusInternalServerError, "Failed to get admin stats from database", err)
}
anonymousDeviceExpiration := 30 * 24 * time.Hour
devicesCount, err := hs.anonService.CountDevices(c.Req.Context(), time.Now().Add(-anonymousDeviceExpiration), time.Now().Add(time.Minute))
if err != nil {
return response.Error(500, "Failed to get anon stats from database", err)
return response.Error(http.StatusInternalServerError, "Failed to get anon stats from database", err)
}
adminStats.AnonymousStats.ActiveDevices = devicesCount

View File

@ -3,6 +3,7 @@ package api
import (
"context"
"errors"
"net/http"
"github.com/grafana/grafana/pkg/api/response"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
@ -26,7 +27,7 @@ import (
func (hs *HTTPServer) AdminProvisioningReloadDashboards(c *contextmodel.ReqContext) response.Response {
err := hs.ProvisioningService.ProvisionDashboards(c.Req.Context())
if err != nil && !errors.Is(err, context.Canceled) {
return response.Error(500, "", err)
return response.Error(http.StatusInternalServerError, "", err)
}
return response.Success("Dashboards config reloaded")
}
@ -49,7 +50,7 @@ func (hs *HTTPServer) AdminProvisioningReloadDashboards(c *contextmodel.ReqConte
func (hs *HTTPServer) AdminProvisioningReloadDatasources(c *contextmodel.ReqContext) response.Response {
err := hs.ProvisioningService.ProvisionDatasources(c.Req.Context())
if err != nil {
return response.Error(500, "", err)
return response.Error(http.StatusInternalServerError, "", err)
}
return response.Success("Datasources config reloaded")
}
@ -72,7 +73,7 @@ func (hs *HTTPServer) AdminProvisioningReloadDatasources(c *contextmodel.ReqCont
func (hs *HTTPServer) AdminProvisioningReloadPlugins(c *contextmodel.ReqContext) response.Response {
err := hs.ProvisioningService.ProvisionPlugins(c.Req.Context())
if err != nil {
return response.Error(500, "Failed to reload plugins config", err)
return response.Error(http.StatusInternalServerError, "Failed to reload plugins config", err)
}
return response.Success("Plugins config reloaded")
}
@ -95,7 +96,7 @@ func (hs *HTTPServer) AdminProvisioningReloadPlugins(c *contextmodel.ReqContext)
func (hs *HTTPServer) AdminProvisioningReloadNotifications(c *contextmodel.ReqContext) response.Response {
err := hs.ProvisioningService.ProvisionNotifications(c.Req.Context())
if err != nil {
return response.Error(500, "", err)
return response.Error(http.StatusInternalServerError, "", err)
}
return response.Success("Notifications config reloaded")
}
@ -103,7 +104,7 @@ func (hs *HTTPServer) AdminProvisioningReloadNotifications(c *contextmodel.ReqCo
func (hs *HTTPServer) AdminProvisioningReloadAlerting(c *contextmodel.ReqContext) response.Response {
err := hs.ProvisioningService.ProvisionAlerting(c.Req.Context())
if err != nil {
return response.Error(500, "", err)
return response.Error(http.StatusInternalServerError, "", err)
}
return response.Success("Alerting config reloaded")
}

View File

@ -196,10 +196,10 @@ func (hs *HTTPServer) AdminUpdateUserPermissions(c *contextmodel.ReqContext) res
err = hs.userService.UpdatePermissions(c.Req.Context(), userID, form.IsGrafanaAdmin)
if err != nil {
if errors.Is(err, user.ErrLastGrafanaAdmin) {
return response.Error(400, user.ErrLastGrafanaAdmin.Error(), nil)
return response.Error(http.StatusBadRequest, user.ErrLastGrafanaAdmin.Error(), nil)
}
return response.Error(500, "Failed to update user permissions", err)
return response.Error(http.StatusInternalServerError, "Failed to update user permissions", err)
}
return response.Success("User permissions updated")
@ -230,9 +230,9 @@ func (hs *HTTPServer) AdminDeleteUser(c *contextmodel.ReqContext) response.Respo
if err := hs.userService.Delete(c.Req.Context(), &cmd); err != nil {
if errors.Is(err, user.ErrUserNotFound) {
return response.Error(404, user.ErrUserNotFound.Error(), nil)
return response.Error(http.StatusNotFound, user.ErrUserNotFound.Error(), nil)
}
return response.Error(500, "Failed to delete user", err)
return response.Error(http.StatusInternalServerError, "Failed to delete user", err)
}
g, ctx := errgroup.WithContext(c.Req.Context())
@ -285,7 +285,7 @@ func (hs *HTTPServer) AdminDeleteUser(c *contextmodel.ReqContext) response.Respo
return nil
})
if err := g.Wait(); err != nil {
return response.Error(500, "Failed to delete user", err)
return response.Error(http.StatusInternalServerError, "Failed to delete user", err)
}
return response.Success("User deleted")
@ -315,20 +315,20 @@ func (hs *HTTPServer) AdminDisableUser(c *contextmodel.ReqContext) response.Resp
// External users shouldn't be disabled from API
authInfoQuery := &login.GetAuthInfoQuery{UserId: userID}
if _, err := hs.authInfoService.GetAuthInfo(c.Req.Context(), authInfoQuery); !errors.Is(err, user.ErrUserNotFound) {
return response.Error(500, "Could not disable external user", nil)
return response.Error(http.StatusInternalServerError, "Could not disable external user", nil)
}
disableCmd := user.DisableUserCommand{UserID: userID, IsDisabled: true}
if err := hs.userService.Disable(c.Req.Context(), &disableCmd); err != nil {
if errors.Is(err, user.ErrUserNotFound) {
return response.Error(404, user.ErrUserNotFound.Error(), nil)
return response.Error(http.StatusNotFound, user.ErrUserNotFound.Error(), nil)
}
return response.Error(500, "Failed to disable user", err)
return response.Error(http.StatusInternalServerError, "Failed to disable user", err)
}
err = hs.AuthTokenService.RevokeAllUserTokens(c.Req.Context(), userID)
if err != nil {
return response.Error(500, "Failed to disable user", err)
return response.Error(http.StatusInternalServerError, "Failed to disable user", err)
}
return response.Success("User disabled")
@ -358,15 +358,15 @@ func (hs *HTTPServer) AdminEnableUser(c *contextmodel.ReqContext) response.Respo
// External users shouldn't be disabled from API
authInfoQuery := &login.GetAuthInfoQuery{UserId: userID}
if _, err := hs.authInfoService.GetAuthInfo(c.Req.Context(), authInfoQuery); !errors.Is(err, user.ErrUserNotFound) {
return response.Error(500, "Could not enable external user", nil)
return response.Error(http.StatusInternalServerError, "Could not enable external user", nil)
}
disableCmd := user.DisableUserCommand{UserID: userID, IsDisabled: false}
if err := hs.userService.Disable(c.Req.Context(), &disableCmd); err != nil {
if errors.Is(err, user.ErrUserNotFound) {
return response.Error(404, user.ErrUserNotFound.Error(), nil)
return response.Error(http.StatusNotFound, user.ErrUserNotFound.Error(), nil)
}
return response.Error(500, "Failed to enable user", err)
return response.Error(http.StatusInternalServerError, "Failed to enable user", err)
}
return response.Success("User enabled")

View File

@ -58,7 +58,7 @@ func (hs *HTTPServer) GetAlertStatesForDashboard(c *contextmodel.ReqContext) res
dashboardID := c.QueryInt64("dashboardId")
if dashboardID == 0 {
return response.Error(400, "Missing query parameter dashboardId", nil)
return response.Error(http.StatusBadRequest, "Missing query parameter dashboardId", nil)
}
query := alertmodels.GetAlertStatesForDashboardQuery{
@ -68,7 +68,7 @@ func (hs *HTTPServer) GetAlertStatesForDashboard(c *contextmodel.ReqContext) res
res, err := hs.AlertEngine.AlertStore.GetAlertStatesForDashboard(c.Req.Context(), &query)
if err != nil {
return response.Error(500, "Failed to fetch alert states", err)
return response.Error(http.StatusInternalServerError, "Failed to fetch alert states", err)
}
return response.JSON(http.StatusOK, res)
@ -120,7 +120,7 @@ func (hs *HTTPServer) GetAlerts(c *contextmodel.ReqContext) response.Response {
hits, err := hs.SearchService.SearchHandler(c.Req.Context(), &searchQuery)
if err != nil {
return response.Error(500, "List alerts failed", err)
return response.Error(http.StatusInternalServerError, "List alerts failed", err)
}
for _, d := range hits {
@ -151,7 +151,7 @@ func (hs *HTTPServer) GetAlerts(c *contextmodel.ReqContext) response.Response {
res, err := hs.AlertEngine.AlertStore.HandleAlertsQuery(c.Req.Context(), &query)
if err != nil {
return response.Error(500, "List alerts failed", err)
return response.Error(http.StatusInternalServerError, "List alerts failed", err)
}
for _, alert := range res {
@ -177,19 +177,19 @@ func (hs *HTTPServer) AlertTest(c *contextmodel.ReqContext) response.Response {
return response.Error(http.StatusBadRequest, "bad request data", err)
}
if _, idErr := dto.Dashboard.Get("id").Int64(); idErr != nil {
return response.Error(400, "The dashboard needs to be saved at least once before you can test an alert rule", nil)
return response.Error(http.StatusBadRequest, "The dashboard needs to be saved at least once before you can test an alert rule", nil)
}
res, err := hs.AlertEngine.AlertTest(c.SignedInUser.GetOrgID(), dto.Dashboard, dto.PanelId, c.SignedInUser)
if err != nil {
var validationErr alerting.ValidationError
if errors.As(err, &validationErr) {
return response.Error(422, validationErr.Error(), nil)
return response.Error(http.StatusUnprocessableEntity, validationErr.Error(), nil)
}
if errors.Is(err, datasources.ErrDataSourceAccessDenied) {
return response.Error(403, "Access denied to datasource", err)
return response.Error(http.StatusForbidden, "Access denied to datasource", err)
}
return response.Error(500, "Failed to test rule", err)
return response.Error(http.StatusInternalServerError, "Failed to test rule", err)
}
dtoRes := &dtos.AlertTestResult{
@ -234,7 +234,7 @@ func (hs *HTTPServer) GetAlert(c *contextmodel.ReqContext) response.Response {
res, err := hs.AlertEngine.AlertStore.GetAlertById(c.Req.Context(), &query)
if err != nil {
return response.Error(500, "List alerts failed", err)
return response.Error(http.StatusInternalServerError, "List alerts failed", err)
}
return response.JSON(http.StatusOK, &res)
@ -266,7 +266,7 @@ func (hs *HTTPServer) GetAlertNotifiers() func(*contextmodel.ReqContext) respons
func (hs *HTTPServer) GetAlertNotificationLookup(c *contextmodel.ReqContext) response.Response {
alertNotifications, err := hs.getAlertNotificationsInternal(c)
if err != nil {
return response.Error(500, "Failed to get alert notifications", err)
return response.Error(http.StatusInternalServerError, "Failed to get alert notifications", err)
}
result := make([]*dtos.AlertNotificationLookup, 0)
@ -292,7 +292,7 @@ func (hs *HTTPServer) GetAlertNotificationLookup(c *contextmodel.ReqContext) res
func (hs *HTTPServer) GetAlertNotifications(c *contextmodel.ReqContext) response.Response {
alertNotifications, err := hs.getAlertNotificationsInternal(c)
if err != nil {
return response.Error(500, "Failed to get alert notifications", err)
return response.Error(http.StatusInternalServerError, "Failed to get alert notifications", err)
}
result := make([]*dtos.AlertNotification, 0)
@ -332,16 +332,16 @@ func (hs *HTTPServer) GetAlertNotificationByID(c *contextmodel.ReqContext) respo
}
if query.ID == 0 {
return response.Error(404, "Alert notification not found", nil)
return response.Error(http.StatusNotFound, "Alert notification not found", nil)
}
res, err := hs.AlertNotificationService.GetAlertNotifications(c.Req.Context(), query)
if err != nil {
return response.Error(500, "Failed to get alert notifications", err)
return response.Error(http.StatusInternalServerError, "Failed to get alert notifications", err)
}
if res == nil {
return response.Error(404, "Alert notification not found", nil)
return response.Error(http.StatusNotFound, "Alert notification not found", nil)
}
return response.JSON(http.StatusOK, dtos.NewAlertNotification(res))
@ -366,16 +366,16 @@ func (hs *HTTPServer) GetAlertNotificationByUID(c *contextmodel.ReqContext) resp
}
if query.UID == "" {
return response.Error(404, "Alert notification not found", nil)
return response.Error(http.StatusNotFound, "Alert notification not found", nil)
}
res, err := hs.AlertNotificationService.GetAlertNotificationsWithUid(c.Req.Context(), query)
if err != nil {
return response.Error(500, "Failed to get alert notifications", err)
return response.Error(http.StatusInternalServerError, "Failed to get alert notifications", err)
}
if res == nil {
return response.Error(404, "Alert notification not found", nil)
return response.Error(http.StatusNotFound, "Alert notification not found", nil)
}
return response.JSON(http.StatusOK, dtos.NewAlertNotification(res))
@ -403,13 +403,13 @@ func (hs *HTTPServer) CreateAlertNotification(c *contextmodel.ReqContext) respon
res, err := hs.AlertNotificationService.CreateAlertNotificationCommand(c.Req.Context(), &cmd)
if err != nil {
if errors.Is(err, alertmodels.ErrAlertNotificationWithSameNameExists) || errors.Is(err, alertmodels.ErrAlertNotificationWithSameUIDExists) {
return response.Error(409, "Failed to create alert notification", err)
return response.Error(http.StatusConflict, "Failed to create alert notification", err)
}
var alertingErr alerting.ValidationError
if errors.As(err, &alertingErr) {
return response.Error(400, err.Error(), err)
return response.Error(http.StatusBadRequest, err.Error(), err)
}
return response.Error(500, "Failed to create alert notification", err)
return response.Error(http.StatusInternalServerError, "Failed to create alert notification", err)
}
return response.JSON(http.StatusOK, dtos.NewAlertNotification(res))
@ -436,18 +436,18 @@ func (hs *HTTPServer) UpdateAlertNotification(c *contextmodel.ReqContext) respon
err := hs.fillWithSecureSettingsData(c.Req.Context(), &cmd)
if err != nil {
return response.Error(500, "Failed to update alert notification", err)
return response.Error(http.StatusInternalServerError, "Failed to update alert notification", err)
}
if _, err := hs.AlertNotificationService.UpdateAlertNotification(c.Req.Context(), &cmd); err != nil {
if errors.Is(err, alertmodels.ErrAlertNotificationNotFound) {
return response.Error(404, err.Error(), err)
return response.Error(http.StatusNotFound, err.Error(), err)
}
var alertingErr alerting.ValidationError
if errors.As(err, &alertingErr) {
return response.Error(400, err.Error(), err)
return response.Error(http.StatusBadRequest, err.Error(), err)
}
return response.Error(500, "Failed to update alert notification", err)
return response.Error(http.StatusInternalServerError, "Failed to update alert notification", err)
}
query := alertmodels.GetAlertNotificationsQuery{
@ -457,7 +457,7 @@ func (hs *HTTPServer) UpdateAlertNotification(c *contextmodel.ReqContext) respon
res, err := hs.AlertNotificationService.GetAlertNotifications(c.Req.Context(), &query)
if err != nil {
return response.Error(500, "Failed to get alert notification", err)
return response.Error(http.StatusInternalServerError, "Failed to get alert notification", err)
}
return response.JSON(http.StatusOK, dtos.NewAlertNotification(res))
@ -485,14 +485,14 @@ func (hs *HTTPServer) UpdateAlertNotificationByUID(c *contextmodel.ReqContext) r
err := hs.fillWithSecureSettingsDataByUID(c.Req.Context(), &cmd)
if err != nil {
return response.Error(500, "Failed to update alert notification", err)
return response.Error(http.StatusInternalServerError, "Failed to update alert notification", err)
}
if _, err := hs.AlertNotificationService.UpdateAlertNotificationWithUid(c.Req.Context(), &cmd); err != nil {
if errors.Is(err, alertmodels.ErrAlertNotificationNotFound) {
return response.Error(404, err.Error(), nil)
return response.Error(http.StatusNotFound, err.Error(), nil)
}
return response.Error(500, "Failed to update alert notification", err)
return response.Error(http.StatusInternalServerError, "Failed to update alert notification", err)
}
query := alertmodels.GetAlertNotificationsWithUidQuery{
@ -502,7 +502,7 @@ func (hs *HTTPServer) UpdateAlertNotificationByUID(c *contextmodel.ReqContext) r
res, err := hs.AlertNotificationService.GetAlertNotificationsWithUid(c.Req.Context(), &query)
if err != nil {
return response.Error(500, "Failed to get alert notification", err)
return response.Error(http.StatusInternalServerError, "Failed to get alert notification", err)
}
return response.JSON(http.StatusOK, dtos.NewAlertNotification(res))
@ -591,9 +591,9 @@ func (hs *HTTPServer) DeleteAlertNotification(c *contextmodel.ReqContext) respon
if err := hs.AlertNotificationService.DeleteAlertNotification(c.Req.Context(), &cmd); err != nil {
if errors.Is(err, alertmodels.ErrAlertNotificationNotFound) {
return response.Error(404, err.Error(), nil)
return response.Error(http.StatusNotFound, err.Error(), nil)
}
return response.Error(500, "Failed to delete alert notification", err)
return response.Error(http.StatusInternalServerError, "Failed to delete alert notification", err)
}
return response.Success("Notification deleted")
@ -619,9 +619,9 @@ func (hs *HTTPServer) DeleteAlertNotificationByUID(c *contextmodel.ReqContext) r
if err := hs.AlertNotificationService.DeleteAlertNotificationWithUid(c.Req.Context(), &cmd); err != nil {
if errors.Is(err, alertmodels.ErrAlertNotificationNotFound) {
return response.Error(404, err.Error(), nil)
return response.Error(http.StatusNotFound, err.Error(), nil)
}
return response.Error(500, "Failed to delete alert notification", err)
return response.Error(http.StatusInternalServerError, "Failed to delete alert notification", err)
}
return response.JSON(http.StatusOK, util.DynMap{
@ -659,14 +659,14 @@ func (hs *HTTPServer) NotificationTest(c *contextmodel.ReqContext) response.Resp
if err := hs.AlertNotificationService.HandleNotificationTestCommand(c.Req.Context(), cmd); err != nil {
if errors.Is(err, notifications.ErrSmtpNotEnabled) {
return response.Error(412, err.Error(), err)
return response.Error(http.StatusPreconditionFailed, err.Error(), err)
}
var alertingErr alerting.ValidationError
if errors.As(err, &alertingErr) {
return response.Error(400, err.Error(), err)
return response.Error(http.StatusBadRequest, err.Error(), err)
}
return response.Error(500, "Failed to send alert notifications", err)
return response.Error(http.StatusInternalServerError, "Failed to send alert notifications", err)
}
return response.Success("Test notification sent")
@ -704,7 +704,7 @@ func (hs *HTTPServer) PauseAlert(legacyAlertingEnabled *bool) func(c *contextmod
query := alertmodels.GetAlertByIdQuery{ID: alertID}
res, err := hs.AlertEngine.AlertStore.GetAlertById(c.Req.Context(), &query)
if err != nil {
return response.Error(500, "Get Alert failed", err)
return response.Error(http.StatusInternalServerError, "Get Alert failed", err)
}
guardian, err := guardian.New(c.Req.Context(), res.DashboardID, c.SignedInUser.GetOrgID(), c.SignedInUser)
@ -713,10 +713,10 @@ func (hs *HTTPServer) PauseAlert(legacyAlertingEnabled *bool) func(c *contextmod
}
if canEdit, err := guardian.CanEdit(); err != nil || !canEdit {
if err != nil {
return response.Error(500, "Error while checking permissions for Alert", err)
return response.Error(http.StatusInternalServerError, "Error while checking permissions for Alert", err)
}
return response.Error(403, "Access denied to this dashboard and alert", nil)
return response.Error(http.StatusForbidden, "Access denied to this dashboard and alert", nil)
}
// Alert state validation
@ -737,7 +737,7 @@ func (hs *HTTPServer) PauseAlert(legacyAlertingEnabled *bool) func(c *contextmod
}
if err := hs.AlertEngine.AlertStore.PauseAlert(c.Req.Context(), &cmd); err != nil {
return response.Error(500, "", err)
return response.Error(http.StatusInternalServerError, "", err)
}
resp := alertmodels.AlertStateUnknown
@ -782,7 +782,7 @@ func (hs *HTTPServer) PauseAllAlerts(legacyAlertingEnabled *bool) func(c *contex
}
if err := hs.AlertEngine.AlertStore.PauseAllAlerts(c.Req.Context(), &updateCmd); err != nil {
return response.Error(500, "Failed to pause alerts", err)
return response.Error(http.StatusInternalServerError, "Failed to pause alerts", err)
}
resp := alertmodels.AlertStatePending

View File

@ -62,7 +62,7 @@ func (hs *HTTPServer) GetAnnotations(c *contextmodel.ReqContext) response.Respon
items, err := hs.annotationsRepo.Find(c.Req.Context(), query)
if err != nil {
return response.Error(500, "Failed to get annotations", err)
return response.Error(http.StatusInternalServerError, "Failed to get annotations", err)
}
// since there are several annotations per dashboard, we can cache dashboard uid
@ -138,7 +138,7 @@ func (hs *HTTPServer) PostAnnotation(c *contextmodel.ReqContext) response.Respon
if cmd.Text == "" {
err := &AnnotationError{"text field should not be empty"}
return response.Error(400, "Failed to save annotation", err)
return response.Error(http.StatusBadRequest, "Failed to save annotation", err)
}
userID, err := identity.UserIdentifier(c.SignedInUser.GetNamespacedID())
@ -160,9 +160,9 @@ func (hs *HTTPServer) PostAnnotation(c *contextmodel.ReqContext) response.Respon
if err := hs.annotationsRepo.Save(c.Req.Context(), &item); err != nil {
if errors.Is(err, annotations.ErrTimerangeMissing) {
return response.Error(400, "Failed to save annotation", err)
return response.Error(http.StatusBadRequest, "Failed to save annotation", err)
}
return response.ErrOrFallback(500, "Failed to save annotation", err)
return response.ErrOrFallback(http.StatusInternalServerError, "Failed to save annotation", err)
}
startID := item.ID
@ -200,7 +200,7 @@ func (hs *HTTPServer) PostGraphiteAnnotation(c *contextmodel.ReqContext) respons
}
if cmd.What == "" {
err := &AnnotationError{"what field should not be empty"}
return response.Error(400, "Failed to save Graphite annotation", err)
return response.Error(http.StatusBadRequest, "Failed to save Graphite annotation", err)
}
text := formatGraphiteAnnotation(cmd.What, cmd.Data)
@ -220,12 +220,12 @@ func (hs *HTTPServer) PostGraphiteAnnotation(c *contextmodel.ReqContext) respons
tagsArray = append(tagsArray, tagStr)
} else {
err := &AnnotationError{"tag should be a string"}
return response.Error(400, "Failed to save Graphite annotation", err)
return response.Error(http.StatusBadRequest, "Failed to save Graphite annotation", err)
}
}
default:
err := &AnnotationError{"unsupported tags format"}
return response.Error(400, "Failed to save Graphite annotation", err)
return response.Error(http.StatusBadRequest, "Failed to save Graphite annotation", err)
}
userID, err := identity.UserIdentifier(c.SignedInUser.GetNamespacedID())
@ -242,7 +242,7 @@ func (hs *HTTPServer) PostGraphiteAnnotation(c *contextmodel.ReqContext) respons
}
if err := hs.annotationsRepo.Save(c.Req.Context(), &item); err != nil {
return response.ErrOrFallback(500, "Failed to save Graphite annotation", err)
return response.ErrOrFallback(http.StatusInternalServerError, "Failed to save Graphite annotation", err)
}
return response.JSON(http.StatusOK, util.DynMap{
@ -307,7 +307,7 @@ func (hs *HTTPServer) UpdateAnnotation(c *contextmodel.ReqContext) response.Resp
}
if err := hs.annotationsRepo.Update(c.Req.Context(), &item); err != nil {
return response.ErrOrFallback(500, "Failed to update annotation", err)
return response.ErrOrFallback(http.StatusInternalServerError, "Failed to update annotation", err)
}
return response.Success("Annotation updated")
@ -386,7 +386,7 @@ func (hs *HTTPServer) PatchAnnotation(c *contextmodel.ReqContext) response.Respo
}
if err := hs.annotationsRepo.Update(c.Req.Context(), &existing); err != nil {
return response.ErrOrFallback(500, "Failed to update annotation", err)
return response.ErrOrFallback(http.StatusInternalServerError, "Failed to update annotation", err)
}
return response.Success("Annotation patched")
@ -459,7 +459,7 @@ func (hs *HTTPServer) MassDeleteAnnotations(c *contextmodel.ReqContext) response
err = hs.annotationsRepo.Delete(c.Req.Context(), deleteParams)
if err != nil {
return response.Error(500, "Failed to delete annotations", err)
return response.Error(http.StatusInternalServerError, "Failed to delete annotations", err)
}
return response.Success("Annotations deleted")
@ -488,7 +488,7 @@ func (hs *HTTPServer) GetAnnotationByID(c *contextmodel.ReqContext) response.Res
annotation.AvatarURL = dtos.GetGravatarUrl(hs.Cfg, annotation.Email)
}
return response.JSON(200, annotation)
return response.JSON(http.StatusOK, annotation)
}
// swagger:route DELETE /annotations/{annotation_id} annotations deleteAnnotationByID
@ -524,7 +524,7 @@ func (hs *HTTPServer) DeleteAnnotationByID(c *contextmodel.ReqContext) response.
ID: annotationID,
})
if err != nil {
return response.Error(500, "Failed to delete annotation", err)
return response.Error(http.StatusInternalServerError, "Failed to delete annotation", err)
}
return response.Success("Annotation deleted")
@ -560,11 +560,11 @@ func findAnnotationByID(ctx context.Context, repo annotations.Repository, annota
items, err := repo.Find(ctx, query)
if err != nil {
return nil, response.Error(500, "Failed to find annotation", err)
return nil, response.Error(http.StatusInternalServerError, "Failed to find annotation", err)
}
if len(items) == 0 {
return nil, response.Error(404, "Annotation not found", nil)
return nil, response.Error(http.StatusNotFound, "Annotation not found", nil)
}
return items[0], nil
@ -589,7 +589,7 @@ func (hs *HTTPServer) GetAnnotationTags(c *contextmodel.ReqContext) response.Res
result, err := hs.annotationsRepo.FindTags(c.Req.Context(), query)
if err != nil {
return response.Error(500, "Failed to find annotation tags", err)
return response.Error(http.StatusInternalServerError, "Failed to find annotation tags", err)
}
return response.JSON(http.StatusOK, annotations.GetAnnotationTagsResponse{Result: result})

View File

@ -2,6 +2,7 @@ package apierrors
import (
"errors"
"net/http"
"github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/services/dashboards"
@ -19,25 +20,25 @@ func ToFolderErrorResponse(err error) response.Response {
errors.Is(err, dashboards.ErrDashboardTypeMismatch) ||
errors.Is(err, dashboards.ErrDashboardInvalidUid) ||
errors.Is(err, dashboards.ErrDashboardUidTooLong) {
return response.Error(400, err.Error(), nil)
return response.Error(http.StatusBadRequest, err.Error(), nil)
}
if errors.Is(err, dashboards.ErrFolderAccessDenied) {
return response.Error(403, "Access denied", err)
return response.Error(http.StatusForbidden, "Access denied", err)
}
if errors.Is(err, dashboards.ErrFolderNotFound) {
return response.JSON(404, util.DynMap{"status": "not-found", "message": dashboards.ErrFolderNotFound.Error()})
return response.JSON(http.StatusNotFound, util.DynMap{"status": "not-found", "message": dashboards.ErrFolderNotFound.Error()})
}
if errors.Is(err, dashboards.ErrFolderSameNameExists) ||
errors.Is(err, dashboards.ErrFolderWithSameUIDExists) {
return response.Error(409, err.Error(), nil)
return response.Error(http.StatusConflict, err.Error(), nil)
}
if errors.Is(err, dashboards.ErrFolderVersionMismatch) {
return response.JSON(412, util.DynMap{"status": "version-mismatch", "message": dashboards.ErrFolderVersionMismatch.Error()})
return response.JSON(http.StatusPreconditionFailed, util.DynMap{"status": "version-mismatch", "message": dashboards.ErrFolderVersionMismatch.Error()})
}
return response.ErrOrFallback(500, "Folder API error", err)
return response.ErrOrFallback(http.StatusInternalServerError, "Folder API error", err)
}

View File

@ -92,9 +92,9 @@ func (hs *HTTPServer) DeleteAPIKey(c *contextmodel.ReqContext) response.Response
if err != nil {
var status int
if errors.Is(err, apikey.ErrNotFound) {
status = 404
status = http.StatusNotFound
} else {
status = 500
status = http.StatusInternalServerError
}
return response.Error(status, "Failed to delete API key", err)
}

View File

@ -61,7 +61,7 @@ func (hs *HTTPServer) GetDashboardPermissionList(c *contextmodel.ReqContext) res
acl, err := hs.getDashboardACL(c.Req.Context(), c.SignedInUser, dash)
if err != nil {
return response.Error(500, "Failed to get dashboard permissions", err)
return response.Error(http.StatusInternalServerError, "Failed to get dashboard permissions", err)
}
filteredACLs := make([]*dashboards.DashboardACLInfoDTO, 0, len(acl))
@ -124,7 +124,7 @@ func (hs *HTTPServer) UpdateDashboardPermissions(c *contextmodel.ReqContext) res
return response.Error(http.StatusBadRequest, "bad request data", err)
}
if err := validatePermissionsUpdate(apiCmd); err != nil {
return response.Error(400, err.Error(), err)
return response.Error(http.StatusBadRequest, err.Error(), err)
}
dashUID := web.Params(c.Req)[":uid"]

View File

@ -108,7 +108,7 @@ func (hs *HTTPServer) GetDashboardSnapshot(c *contextmodel.ReqContext) response.
// expired snapshots should also be removed from db
if snapshot.Expires.Before(time.Now()) {
return response.Error(404, "Dashboard snapshot not found", err)
return response.Error(http.StatusNotFound, "Dashboard snapshot not found", err)
}
dto := dtos.DashboardFullWithMeta{
@ -146,15 +146,15 @@ func (hs *HTTPServer) DeleteDashboardSnapshotByDeleteKey(c *contextmodel.ReqCont
key := web.Params(c.Req)[":deleteKey"]
if len(key) == 0 {
return response.Error(404, "Snapshot not found", nil)
return response.Error(http.StatusNotFound, "Snapshot not found", nil)
}
err := dashboardsnapshots.DeleteWithKey(c.Req.Context(), key, hs.dashboardsnapshotsService)
if err != nil {
if errors.Is(err, dashboardsnapshots.ErrBaseNotFound) {
return response.Error(404, "Snapshot not found", err)
return response.Error(http.StatusNotFound, "Snapshot not found", err)
}
return response.Error(500, "Failed to delete dashboard snapshot", err)
return response.Error(http.StatusInternalServerError, "Failed to delete dashboard snapshot", err)
}
return response.JSON(http.StatusOK, util.DynMap{
@ -269,7 +269,7 @@ func (hs *HTTPServer) SearchDashboardSnapshots(c *contextmodel.ReqContext) respo
searchQueryResult, err := hs.dashboardsnapshotsService.SearchDashboardSnapshots(c.Req.Context(), &searchQuery)
if err != nil {
return response.Error(500, "Search failed", err)
return response.Error(http.StatusInternalServerError, "Search failed", err)
}
dto := make([]*dashboardsnapshots.DashboardSnapshotDTO, len(searchQueryResult))

View File

@ -51,12 +51,12 @@ func (hs *HTTPServer) GetDataSources(c *contextmodel.ReqContext) response.Respon
dataSources, err := hs.DataSourcesService.GetDataSources(c.Req.Context(), &query)
if err != nil {
return response.Error(500, "Failed to query datasources", err)
return response.Error(http.StatusInternalServerError, "Failed to query datasources", err)
}
filtered, err := hs.dsGuardian.New(c.SignedInUser.OrgID, c.SignedInUser).FilterDatasourcesByQueryPermissions(dataSources)
if err != nil {
return response.Error(500, "Failed to query datasources", err)
return response.Error(http.StatusInternalServerError, "Failed to query datasources", err)
}
result := make(dtos.DataSourceList, 0)
@ -125,12 +125,12 @@ func (hs *HTTPServer) GetDataSourceById(c *contextmodel.ReqContext) response.Res
dataSource, err := hs.DataSourcesService.GetDataSource(c.Req.Context(), &query)
if err != nil {
if errors.Is(err, datasources.ErrDataSourceNotFound) {
return response.Error(404, "Data source not found", nil)
return response.Error(http.StatusNotFound, "Data source not found", nil)
}
if errors.Is(err, datasources.ErrDataSourceIdentifierNotSet) {
return response.Error(400, "Datasource id is missing", nil)
return response.Error(http.StatusBadRequest, "Datasource id is missing", nil)
}
return response.Error(500, "Failed to query datasources", err)
return response.Error(http.StatusInternalServerError, "Failed to query datasources", err)
}
dto := hs.convertModelToDtos(c.Req.Context(), dataSource)
@ -165,19 +165,19 @@ func (hs *HTTPServer) DeleteDataSourceById(c *contextmodel.ReqContext) response.
}
if id <= 0 {
return response.Error(400, "Missing valid datasource id", nil)
return response.Error(http.StatusBadRequest, "Missing valid datasource id", nil)
}
ds, err := hs.getRawDataSourceById(c.Req.Context(), id, c.SignedInUser.GetOrgID())
if err != nil {
if errors.Is(err, datasources.ErrDataSourceNotFound) {
return response.Error(404, "Data source not found", nil)
return response.Error(http.StatusNotFound, "Data source not found", nil)
}
return response.Error(400, "Failed to delete datasource", nil)
return response.Error(http.StatusBadRequest, "Failed to delete datasource", nil)
}
if ds.ReadOnly {
return response.Error(403, "Cannot delete read-only data source", nil)
return response.Error(http.StatusForbidden, "Cannot delete read-only data source", nil)
}
cmd := &datasources.DeleteDataSourceCommand{ID: id, OrgID: c.SignedInUser.GetOrgID(), Name: ds.Name}
@ -185,9 +185,9 @@ func (hs *HTTPServer) DeleteDataSourceById(c *contextmodel.ReqContext) response.
err = hs.DataSourcesService.DeleteDataSource(c.Req.Context(), cmd)
if err != nil {
if errors.As(err, &secretsPluginError) {
return response.Error(500, "Failed to delete datasource: "+err.Error(), err)
return response.Error(http.StatusInternalServerError, "Failed to delete datasource: "+err.Error(), err)
}
return response.Error(500, "Failed to delete datasource", err)
return response.Error(http.StatusInternalServerError, "Failed to delete datasource", err)
}
hs.Live.HandleDatasourceDelete(c.SignedInUser.GetOrgID(), ds.UID)
@ -244,19 +244,19 @@ func (hs *HTTPServer) DeleteDataSourceByUID(c *contextmodel.ReqContext) response
uid := web.Params(c.Req)[":uid"]
if uid == "" {
return response.Error(400, "Missing datasource uid", nil)
return response.Error(http.StatusBadRequest, "Missing datasource uid", nil)
}
ds, err := hs.getRawDataSourceByUID(c.Req.Context(), uid, c.SignedInUser.GetOrgID())
if err != nil {
if errors.Is(err, datasources.ErrDataSourceNotFound) {
return response.Error(404, "Data source not found", nil)
return response.Error(http.StatusNotFound, "Data source not found", nil)
}
return response.Error(400, "Failed to delete datasource", nil)
return response.Error(http.StatusBadRequest, "Failed to delete datasource", nil)
}
if ds.ReadOnly {
return response.Error(403, "Cannot delete read-only data source", nil)
return response.Error(http.StatusForbidden, "Cannot delete read-only data source", nil)
}
cmd := &datasources.DeleteDataSourceCommand{UID: uid, OrgID: c.SignedInUser.GetOrgID(), Name: ds.Name}
@ -264,9 +264,9 @@ func (hs *HTTPServer) DeleteDataSourceByUID(c *contextmodel.ReqContext) response
err = hs.DataSourcesService.DeleteDataSource(c.Req.Context(), cmd)
if err != nil {
if errors.As(err, &secretsPluginError) {
return response.Error(500, "Failed to delete datasource: "+err.Error(), err)
return response.Error(http.StatusInternalServerError, "Failed to delete datasource: "+err.Error(), err)
}
return response.Error(500, "Failed to delete datasource", err)
return response.Error(http.StatusInternalServerError, "Failed to delete datasource", err)
}
hs.Live.HandleDatasourceDelete(c.SignedInUser.GetOrgID(), ds.UID)
@ -294,29 +294,29 @@ func (hs *HTTPServer) DeleteDataSourceByName(c *contextmodel.ReqContext) respons
name := web.Params(c.Req)[":name"]
if name == "" {
return response.Error(400, "Missing valid datasource name", nil)
return response.Error(http.StatusBadRequest, "Missing valid datasource name", nil)
}
getCmd := &datasources.GetDataSourceQuery{Name: name, OrgID: c.SignedInUser.GetOrgID()}
dataSource, err := hs.DataSourcesService.GetDataSource(c.Req.Context(), getCmd)
if err != nil {
if errors.Is(err, datasources.ErrDataSourceNotFound) {
return response.Error(404, "Data source not found", nil)
return response.Error(http.StatusNotFound, "Data source not found", nil)
}
return response.Error(500, "Failed to delete datasource", err)
return response.Error(http.StatusInternalServerError, "Failed to delete datasource", err)
}
if dataSource.ReadOnly {
return response.Error(403, "Cannot delete read-only data source", nil)
return response.Error(http.StatusForbidden, "Cannot delete read-only data source", nil)
}
cmd := &datasources.DeleteDataSourceCommand{Name: name, OrgID: c.SignedInUser.GetOrgID()}
err = hs.DataSourcesService.DeleteDataSource(c.Req.Context(), cmd)
if err != nil {
if errors.As(err, &secretsPluginError) {
return response.Error(500, "Failed to delete datasource: "+err.Error(), err)
return response.Error(http.StatusInternalServerError, "Failed to delete datasource: "+err.Error(), err)
}
return response.Error(500, "Failed to delete datasource", err)
return response.Error(http.StatusInternalServerError, "Failed to delete datasource", err)
}
hs.Live.HandleDatasourceDelete(c.SignedInUser.GetOrgID(), dataSource.UID)
@ -528,9 +528,9 @@ func (hs *HTTPServer) UpdateDataSourceByID(c *contextmodel.ReqContext) response.
ds, err := hs.getRawDataSourceById(c.Req.Context(), cmd.ID, cmd.OrgID)
if err != nil {
if errors.Is(err, datasources.ErrDataSourceNotFound) {
return response.Error(404, "Data source not found", nil)
return response.Error(http.StatusNotFound, "Data source not found", nil)
}
return response.Error(500, "Failed to update datasource", err)
return response.Error(http.StatusInternalServerError, "Failed to update datasource", err)
}
// check if LBAC rules have been modified
@ -613,7 +613,7 @@ func checkTeamHTTPHeaderPermissions(hs *HTTPServer, c *contextmodel.ReqContext,
func (hs *HTTPServer) updateDataSourceByID(c *contextmodel.ReqContext, ds *datasources.DataSource, cmd datasources.UpdateDataSourceCommand) response.Response {
if ds.ReadOnly {
return response.Error(403, "Cannot update read-only data source", nil)
return response.Error(http.StatusForbidden, "Cannot update read-only data source", nil)
}
_, err := hs.DataSourcesService.UpdateDataSource(c.Req.Context(), &cmd)
@ -641,9 +641,9 @@ func (hs *HTTPServer) updateDataSourceByID(c *contextmodel.ReqContext, ds *datas
dataSource, err := hs.DataSourcesService.GetDataSource(c.Req.Context(), &query)
if err != nil {
if errors.Is(err, datasources.ErrDataSourceNotFound) {
return response.Error(404, "Data source not found", nil)
return response.Error(http.StatusNotFound, "Data source not found", nil)
}
return response.Error(500, "Failed to query datasource", err)
return response.Error(http.StatusInternalServerError, "Failed to query datasource", err)
}
datasourceDTO := hs.convertModelToDtos(c.Req.Context(), dataSource)
@ -704,9 +704,9 @@ func (hs *HTTPServer) GetDataSourceByName(c *contextmodel.ReqContext) response.R
dataSource, err := hs.DataSourcesService.GetDataSource(c.Req.Context(), &query)
if err != nil {
if errors.Is(err, datasources.ErrDataSourceNotFound) {
return response.Error(404, "Data source not found", nil)
return response.Error(http.StatusNotFound, "Data source not found", nil)
}
return response.Error(500, "Failed to query datasources", err)
return response.Error(http.StatusInternalServerError, "Failed to query datasources", err)
}
dto := hs.convertModelToDtos(c.Req.Context(), dataSource)
@ -732,9 +732,9 @@ func (hs *HTTPServer) GetDataSourceIdByName(c *contextmodel.ReqContext) response
ds, err := hs.DataSourcesService.GetDataSource(c.Req.Context(), &query)
if err != nil {
if errors.Is(err, datasources.ErrDataSourceNotFound) {
return response.Error(404, "Data source not found", nil)
return response.Error(http.StatusNotFound, "Data source not found", nil)
}
return response.Error(500, "Failed to query datasources", err)
return response.Error(http.StatusInternalServerError, "Failed to query datasources", err)
}
dtos := dtos.AnyId{

View File

@ -298,7 +298,7 @@ func (hs *HTTPServer) DeleteFolder(c *contextmodel.ReqContext) response.Response
err := hs.LibraryElementService.DeleteLibraryElementsInFolder(c.Req.Context(), c.SignedInUser, web.Params(c.Req)[":uid"])
if err != nil {
if errors.Is(err, model.ErrFolderHasConnectedLibraryElements) {
return response.Error(403, "Folder could not be deleted because it contains library elements in use", err)
return response.Error(http.StatusForbidden, "Folder could not be deleted because it contains library elements in use", err)
}
return apierrors.ToFolderErrorResponse(err)
}

View File

@ -38,7 +38,7 @@ func (hs *HTTPServer) GetFolderPermissionList(c *contextmodel.ReqContext) respon
acl, err := hs.getFolderACL(c.Req.Context(), c.SignedInUser, folder)
if err != nil {
return response.Error(500, "Failed to get folder permissions", err)
return response.Error(http.StatusInternalServerError, "Failed to get folder permissions", err)
}
filteredACLs := make([]*dashboards.DashboardACLInfoDTO, 0, len(acl))
@ -83,7 +83,7 @@ func (hs *HTTPServer) UpdateFolderPermissions(c *contextmodel.ReqContext) respon
return response.Error(http.StatusBadRequest, "bad request data", err)
}
if err := validatePermissionsUpdate(apiCmd); err != nil {
return response.Error(400, err.Error(), err)
return response.Error(http.StatusBadRequest, err.Error(), err)
}
uid := web.Params(c.Req)[":uid"]

View File

@ -255,7 +255,7 @@ func hashUserIdentifier(identifier string, secret string) string {
func (hs *HTTPServer) Index(c *contextmodel.ReqContext) {
data, err := hs.setIndexViewData(c)
if err != nil {
c.Handle(hs.Cfg, 500, "Failed to get settings", err)
c.Handle(hs.Cfg, http.StatusInternalServerError, "Failed to get settings", err)
return
}
c.HTML(http.StatusOK, "index", data)
@ -263,17 +263,17 @@ func (hs *HTTPServer) Index(c *contextmodel.ReqContext) {
func (hs *HTTPServer) NotFoundHandler(c *contextmodel.ReqContext) {
if c.IsApiRequest() {
c.JsonApiErr(404, "Not found", nil)
c.JsonApiErr(http.StatusNotFound, "Not found", nil)
return
}
data, err := hs.setIndexViewData(c)
if err != nil {
c.Handle(hs.Cfg, 500, "Failed to get settings", err)
c.Handle(hs.Cfg, http.StatusInternalServerError, "Failed to get settings", err)
return
}
c.HTML(404, "index", data)
c.HTML(http.StatusNotFound, "index", data)
}
func (hs *HTTPServer) getThemeForIndexData(themePrefId string, themeURLParam string) *pref.ThemeDTO {

View File

@ -96,7 +96,7 @@ func (hs *HTTPServer) LoginView(c *contextmodel.ReqContext) {
viewData, err := setIndexViewData(hs, c)
if err != nil {
c.Handle(hs.Cfg, 500, "Failed to get settings", err)
c.Handle(hs.Cfg, http.StatusInternalServerError, "Failed to get settings", err)
return
}
@ -196,7 +196,7 @@ func (hs *HTTPServer) LoginAPIPing(c *contextmodel.ReqContext) response.Response
return response.JSON(http.StatusOK, util.DynMap{"message": "Logged in"})
}
return response.Error(401, "Unauthorized", nil)
return response.Error(http.StatusUnauthorized, "Unauthorized", nil)
}
func (hs *HTTPServer) LoginPost(c *contextmodel.ReqContext) response.Response {

View File

@ -216,14 +216,14 @@ func (hs *HTTPServer) GetInviteInfoByCode(c *contextmodel.ReqContext) response.R
queryResult, err := hs.tempUserService.GetTempUserByCode(c.Req.Context(), &query)
if err != nil {
if errors.Is(err, tempuser.ErrTempUserNotFound) {
return response.Error(404, "Invite not found", nil)
return response.Error(http.StatusNotFound, "Invite not found", nil)
}
return response.Error(500, "Failed to get invite", err)
return response.Error(http.StatusInternalServerError, "Failed to get invite", err)
}
invite := queryResult
if invite.Status != tempuser.TmpUserInvitePending {
return response.Error(404, "Invite not found", nil)
return response.Error(http.StatusNotFound, "Invite not found", nil)
}
return response.JSON(http.StatusOK, dtos.InviteInfo{
@ -285,17 +285,17 @@ func (hs *HTTPServer) CompleteInvite(c *contextmodel.ReqContext) response.Respon
usr, err := hs.userService.Create(c.Req.Context(), &cmd)
if err != nil {
if errors.Is(err, user.ErrUserAlreadyExists) {
return response.Error(412, fmt.Sprintf("User with email '%s' or username '%s' already exists", completeInvite.Email, completeInvite.Username), err)
return response.Error(http.StatusPreconditionFailed, fmt.Sprintf("User with email '%s' or username '%s' already exists", completeInvite.Email, completeInvite.Username), err)
}
return response.Error(500, "failed to create user", err)
return response.Error(http.StatusInternalServerError, "failed to create user", err)
}
if err := hs.bus.Publish(c.Req.Context(), &events.SignUpCompleted{
Name: usr.NameOrFallback(),
Email: usr.Email,
}); err != nil {
return response.Error(500, "failed to publish event", err)
return response.Error(http.StatusInternalServerError, "failed to publish event", err)
}
if ok, rsp := hs.applyUserInvite(c.Req.Context(), usr, invite, true); !ok {
@ -304,7 +304,7 @@ func (hs *HTTPServer) CompleteInvite(c *contextmodel.ReqContext) response.Respon
err = hs.loginUserWithUser(usr, c)
if err != nil {
return response.Error(500, "failed to accept invite", err)
return response.Error(http.StatusInternalServerError, "failed to accept invite", err)
}
metrics.MApiUserSignUpCompleted.Inc()
@ -320,7 +320,7 @@ func (hs *HTTPServer) updateTempUserStatus(ctx context.Context, code string, sta
// update temp user status
updateTmpUserCmd := tempuser.UpdateTempUserStatusCommand{Code: code, Status: status}
if err := hs.tempUserService.UpdateTempUserStatus(ctx, &updateTmpUserCmd); err != nil {
return false, response.Error(500, "Failed to update invite status", err)
return false, response.Error(http.StatusInternalServerError, "Failed to update invite status", err)
}
return true, nil
@ -331,7 +331,7 @@ func (hs *HTTPServer) applyUserInvite(ctx context.Context, usr *user.User, invit
addOrgUserCmd := org.AddOrgUserCommand{OrgID: invite.OrgID, UserID: usr.ID, Role: invite.Role}
if err := hs.orgService.AddOrgUser(ctx, &addOrgUserCmd); err != nil {
if !errors.Is(err, org.ErrOrgUserAlreadyAdded) {
return false, response.Error(500, "Error while trying to create org user", err)
return false, response.Error(http.StatusInternalServerError, "Error while trying to create org user", err)
}
}
@ -343,7 +343,7 @@ func (hs *HTTPServer) applyUserInvite(ctx context.Context, usr *user.User, invit
if setActive {
// set org to active
if err := hs.userService.SetUsingOrg(ctx, &user.SetUsingOrgCommand{OrgID: invite.OrgID, UserID: usr.ID}); err != nil {
return false, response.Error(500, "Failed to set org as active", err)
return false, response.Error(http.StatusInternalServerError, "Failed to set org as active", err)
}
}

View File

@ -124,7 +124,7 @@ func (hs *HTTPServer) GetOrgUsersForCurrentOrg(c *contextmodel.ReqContext) respo
})
if err != nil {
return response.Error(500, "Failed to get users for current organization", err)
return response.Error(http.StatusInternalServerError, "Failed to get users for current organization", err)
}
return response.JSON(http.StatusOK, result.OrgUsers)
@ -154,7 +154,7 @@ func (hs *HTTPServer) GetOrgUsersForCurrentOrgLookup(c *contextmodel.ReqContext)
})
if err != nil {
return response.Error(500, "Failed to get users for current organization", err)
return response.Error(http.StatusInternalServerError, "Failed to get users for current organization", err)
}
result := make([]*dtos.UserLookupDTO, 0)
@ -199,7 +199,7 @@ func (hs *HTTPServer) GetOrgUsers(c *contextmodel.ReqContext) response.Response
})
if err != nil {
return response.Error(500, "Failed to get users for organization", err)
return response.Error(http.StatusInternalServerError, "Failed to get users for organization", err)
}
return response.JSON(http.StatusOK, result.OrgUsers)
@ -251,7 +251,7 @@ func (hs *HTTPServer) SearchOrgUsers(c *contextmodel.ReqContext) response.Respon
})
if err != nil {
return response.Error(500, "Failed to get users for organization", err)
return response.Error(http.StatusInternalServerError, "Failed to get users for organization", err)
}
return response.JSON(http.StatusOK, result)
@ -286,7 +286,7 @@ func (hs *HTTPServer) SearchOrgUsersWithPaging(c *contextmodel.ReqContext) respo
result, err := hs.searchOrgUsersHelper(c, query)
if err != nil {
return response.Error(500, "Failed to get users for current organization", err)
return response.Error(http.StatusInternalServerError, "Failed to get users for current organization", err)
}
return response.JSON(http.StatusOK, result)
@ -501,9 +501,9 @@ func (hs *HTTPServer) RemoveOrgUser(c *contextmodel.ReqContext) response.Respons
func (hs *HTTPServer) removeOrgUserHelper(ctx context.Context, cmd *org.RemoveOrgUserCommand) response.Response {
if err := hs.orgService.RemoveOrgUser(ctx, cmd); err != nil {
if errors.Is(err, org.ErrLastOrgAdmin) {
return response.Error(400, "Cannot remove last organization admin", nil)
return response.Error(http.StatusBadRequest, "Cannot remove last organization admin", nil)
}
return response.Error(500, "Failed to remove user from organization", err)
return response.Error(http.StatusInternalServerError, "Failed to remove user from organization", err)
}
if cmd.UserWasDeleted {

View File

@ -92,7 +92,7 @@ func (hs *HTTPServer) SearchPlaylists(c *contextmodel.ReqContext) response.Respo
playlists, err := hs.playlistService.Search(c.Req.Context(), &searchQuery)
if err != nil {
return response.Error(500, "Search failed", err)
return response.Error(http.StatusInternalServerError, "Search failed", err)
}
return response.JSON(http.StatusOK, playlists)
@ -114,7 +114,7 @@ func (hs *HTTPServer) GetPlaylist(c *contextmodel.ReqContext) response.Response
dto, err := hs.playlistService.Get(c.Req.Context(), &cmd)
if err != nil {
return response.Error(500, "Playlist not found", err)
return response.Error(http.StatusInternalServerError, "Playlist not found", err)
}
return response.JSON(http.StatusOK, dto)
@ -136,7 +136,7 @@ func (hs *HTTPServer) GetPlaylistItems(c *contextmodel.ReqContext) response.Resp
dto, err := hs.playlistService.Get(c.Req.Context(), &cmd)
if err != nil {
return response.Error(500, "Playlist not found", err)
return response.Error(http.StatusInternalServerError, "Playlist not found", err)
}
return response.JSON(http.StatusOK, dto.Items)
@ -157,7 +157,7 @@ func (hs *HTTPServer) DeletePlaylist(c *contextmodel.ReqContext) response.Respon
cmd := playlist.DeletePlaylistCommand{UID: uid, OrgId: c.SignedInUser.GetOrgID()}
if err := hs.playlistService.Delete(c.Req.Context(), &cmd); err != nil {
return response.Error(500, "Failed to delete playlist", err)
return response.Error(http.StatusInternalServerError, "Failed to delete playlist", err)
}
return response.JSON(http.StatusOK, "")
@ -182,7 +182,7 @@ func (hs *HTTPServer) CreatePlaylist(c *contextmodel.ReqContext) response.Respon
p, err := hs.playlistService.Create(c.Req.Context(), &cmd)
if err != nil {
return response.Error(500, "Failed to create playlist", err)
return response.Error(http.StatusInternalServerError, "Failed to create playlist", err)
}
return response.JSON(http.StatusOK, p)
@ -208,7 +208,7 @@ func (hs *HTTPServer) UpdatePlaylist(c *contextmodel.ReqContext) response.Respon
_, err := hs.playlistService.Update(c.Req.Context(), &cmd)
if err != nil {
return response.Error(500, "Failed to save playlist", err)
return response.Error(http.StatusInternalServerError, "Failed to save playlist", err)
}
dto, err := hs.playlistService.Get(c.Req.Context(), &playlist.GetPlaylistByUidQuery{
@ -216,7 +216,7 @@ func (hs *HTTPServer) UpdatePlaylist(c *contextmodel.ReqContext) response.Respon
OrgId: c.SignedInUser.GetOrgID(),
})
if err != nil {
return response.Error(500, "Failed to load playlist", err)
return response.Error(http.StatusInternalServerError, "Failed to load playlist", err)
}
return response.JSON(http.StatusOK, dto)
}

View File

@ -247,7 +247,7 @@ func (hs *HTTPServer) UpdatePluginSetting(c *contextmodel.ReqContext) response.R
pluginID := web.Params(c.Req)[":pluginId"]
if _, exists := hs.pluginStore.Plugin(c.Req.Context(), pluginID); !exists {
return response.Error(404, "Plugin not installed", nil)
return response.Error(http.StatusNotFound, "Plugin not installed", nil)
}
cmd.OrgId = c.SignedInUser.GetOrgID()
@ -262,7 +262,7 @@ func (hs *HTTPServer) UpdatePluginSetting(c *contextmodel.ReqContext) response.R
OrgID: cmd.OrgId,
EncryptedSecureJSONData: cmd.EncryptedSecureJsonData,
}); err != nil {
return response.Error(500, "Failed to update plugin setting", err)
return response.Error(http.StatusInternalServerError, "Failed to update plugin setting", err)
}
hs.pluginContextProvider.InvalidateSettingsCache(c.Req.Context(), pluginID)

View File

@ -18,7 +18,7 @@ import (
func (hs *HTTPServer) RenderToPng(c *contextmodel.ReqContext) {
queryReader, err := util.NewURLQueryReader(c.Req.URL)
if err != nil {
c.Handle(hs.Cfg, 400, "Render parameters error", err)
c.Handle(hs.Cfg, http.StatusBadRequest, "Render parameters error", err)
return
}
@ -36,7 +36,7 @@ func (hs *HTTPServer) RenderToPng(c *contextmodel.ReqContext) {
timeout, err := strconv.Atoi(queryReader.Get("timeout", "60"))
if err != nil {
c.Handle(hs.Cfg, 400, "Render parameters error", fmt.Errorf("cannot parse timeout as int: %s", err))
c.Handle(hs.Cfg, http.StatusBadRequest, "Render parameters error", fmt.Errorf("cannot parse timeout as int: %s", err))
return
}
@ -79,11 +79,11 @@ func (hs *HTTPServer) RenderToPng(c *contextmodel.ReqContext) {
}, nil)
if err != nil {
if errors.Is(err, rendering.ErrTimeout) {
c.Handle(hs.Cfg, 500, err.Error(), err)
c.Handle(hs.Cfg, http.StatusInternalServerError, err.Error(), err)
return
}
c.Handle(hs.Cfg, 500, "Rendering failed.", err)
c.Handle(hs.Cfg, http.StatusInternalServerError, "Rendering failed.", err)
return
}

View File

@ -316,7 +316,7 @@ func Respond(status int, body any) *NormalResponse {
default:
var err error
if b, err = json.Marshal(body); err != nil {
return Error(500, "body json marshal", err)
return Error(http.StatusInternalServerError, "body json marshal", err)
}
}

View File

@ -1,6 +1,8 @@
package routing
import (
"net/http"
"github.com/grafana/grafana/pkg/api/response"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/web"
@ -8,7 +10,7 @@ import (
var (
ServerError = func(err error) response.Response {
return response.Error(500, "Server error", err)
return response.Error(http.StatusInternalServerError, "Server error", err)
}
)

View File

@ -31,7 +31,7 @@ func (hs *HTTPServer) Search(c *contextmodel.ReqContext) response.Response {
permission := dashboardaccess.PERMISSION_VIEW
if limit > 5000 {
return response.Error(422, "Limit is above maximum allowed (5000), use page parameter to access hits beyond limit", nil)
return response.Error(http.StatusUnprocessableEntity, "Limit is above maximum allowed (5000), use page parameter to access hits beyond limit", nil)
}
if c.Query("permission") == "Edit" {
@ -67,7 +67,7 @@ func (hs *HTTPServer) Search(c *contextmodel.ReqContext) response.Response {
bothFolderIds := len(folderIDs) > 0 && len(folderUIDs) > 0
if bothDashboardIds || bothFolderIds {
return response.Error(400, "search supports UIDs or IDs, not both", nil)
return response.Error(http.StatusBadRequest, "search supports UIDs or IDs, not both", nil)
}
searchQuery := search.Query{
@ -89,7 +89,7 @@ func (hs *HTTPServer) Search(c *contextmodel.ReqContext) response.Response {
hits, err := hs.SearchService.SearchHandler(c.Req.Context(), &searchQuery)
if err != nil {
return response.Error(500, "Search failed", err)
return response.Error(http.StatusInternalServerError, "Search failed", err)
}
defer c.TimeRequest(metrics.MApiDashboardSearch)

View File

@ -34,7 +34,7 @@ func (hs *HTTPServer) SignUp(c *contextmodel.ReqContext) response.Response {
return response.Error(http.StatusBadRequest, "bad request data", err)
}
if !hs.Cfg.AllowUserSignUp {
return response.Error(401, "User signup is disabled", nil)
return response.Error(http.StatusUnauthorized, "User signup is disabled", nil)
}
form.Email, err = ValidateAndNormalizeEmail(form.Email)
@ -45,7 +45,7 @@ func (hs *HTTPServer) SignUp(c *contextmodel.ReqContext) response.Response {
existing := user.GetUserByLoginQuery{LoginOrEmail: form.Email}
_, err = hs.userService.GetByLogin(c.Req.Context(), &existing)
if err == nil {
return response.Error(422, "User with same email address already exists", nil)
return response.Error(http.StatusUnprocessableEntity, "User with same email address already exists", nil)
}
userID, errID := identity.UserIdentifier(c.SignedInUser.GetNamespacedID())
@ -60,19 +60,19 @@ func (hs *HTTPServer) SignUp(c *contextmodel.ReqContext) response.Response {
cmd.InvitedByUserID = userID
cmd.Code, err = util.GetRandomString(20)
if err != nil {
return response.Error(500, "Failed to generate random string", err)
return response.Error(http.StatusInternalServerError, "Failed to generate random string", err)
}
cmd.RemoteAddr = c.RemoteAddr()
if _, err := hs.tempUserService.CreateTempUser(c.Req.Context(), &cmd); err != nil {
return response.Error(500, "Failed to create signup", err)
return response.Error(http.StatusInternalServerError, "Failed to create signup", err)
}
if err := hs.bus.Publish(c.Req.Context(), &events.SignUpStarted{
Email: form.Email,
Code: cmd.Code,
}); err != nil {
return response.Error(500, "Failed to publish event", err)
return response.Error(http.StatusInternalServerError, "Failed to publish event", err)
}
metrics.MApiUserSignUpStarted.Inc()
@ -86,7 +86,7 @@ func (hs *HTTPServer) SignUpStep2(c *contextmodel.ReqContext) response.Response
return response.Error(http.StatusBadRequest, "bad request data", err)
}
if !hs.Cfg.AllowUserSignUp {
return response.Error(401, "User signup is disabled", nil)
return response.Error(http.StatusUnauthorized, "User signup is disabled", nil)
}
form.Email = strings.TrimSpace(form.Email)
@ -111,10 +111,10 @@ func (hs *HTTPServer) SignUpStep2(c *contextmodel.ReqContext) response.Response
usr, err := hs.userService.Create(c.Req.Context(), &createUserCmd)
if err != nil {
if errors.Is(err, user.ErrUserAlreadyExists) {
return response.Error(401, "User with same email address already exists", nil)
return response.Error(http.StatusUnauthorized, "User with same email address already exists", nil)
}
return response.Error(500, "Failed to create user", err)
return response.Error(http.StatusInternalServerError, "Failed to create user", err)
}
// publish signup event
@ -122,7 +122,7 @@ func (hs *HTTPServer) SignUpStep2(c *contextmodel.ReqContext) response.Response
Email: usr.Email,
Name: usr.NameOrFallback(),
}); err != nil {
return response.Error(500, "Failed to publish event", err)
return response.Error(http.StatusInternalServerError, "Failed to publish event", err)
}
// mark temp user as completed
@ -134,7 +134,7 @@ func (hs *HTTPServer) SignUpStep2(c *contextmodel.ReqContext) response.Response
invitesQuery := tempuser.GetTempUsersQuery{Email: form.Email, Status: tempuser.TmpUserInvitePending}
invitesQueryResult, err := hs.tempUserService.GetTempUsersQuery(c.Req.Context(), &invitesQuery)
if err != nil {
return response.Error(500, "Failed to query database for invites", err)
return response.Error(http.StatusInternalServerError, "Failed to query database for invites", err)
}
apiResponse := util.DynMap{"message": "User sign up completed successfully", "code": "redirect-to-landing-page"}
@ -147,7 +147,7 @@ func (hs *HTTPServer) SignUpStep2(c *contextmodel.ReqContext) response.Response
err = hs.loginUserWithUser(usr, c)
if err != nil {
return response.Error(500, "failed to login user", err)
return response.Error(http.StatusInternalServerError, "failed to login user", err)
}
metrics.MApiUserSignUpCompleted.Inc()
@ -161,14 +161,14 @@ func (hs *HTTPServer) verifyUserSignUpEmail(ctx context.Context, email string, c
queryResult, err := hs.tempUserService.GetTempUserByCode(ctx, &query)
if err != nil {
if errors.Is(err, tempuser.ErrTempUserNotFound) {
return false, response.Error(404, "Invalid email verification code", nil)
return false, response.Error(http.StatusNotFound, "Invalid email verification code", nil)
}
return false, response.Error(500, "Failed to read temp user", err)
return false, response.Error(http.StatusInternalServerError, "Failed to read temp user", err)
}
tempUser := queryResult
if tempUser.Email != email {
return false, response.Error(404, "Email verification code does not match email", nil)
return false, response.Error(http.StatusNotFound, "Email verification code does not match email", nil)
}
return true, nil

View File

@ -66,9 +66,9 @@ func (hs *HTTPServer) getUserUserProfile(c *contextmodel.ReqContext, userID int6
userProfile, err := hs.userService.GetProfile(c.Req.Context(), &query)
if err != nil {
if errors.Is(err, user.ErrUserNotFound) {
return response.Error(404, user.ErrUserNotFound.Error(), nil)
return response.Error(http.StatusNotFound, user.ErrUserNotFound.Error(), nil)
}
return response.Error(500, "Failed to get user", err)
return response.Error(http.StatusInternalServerError, "Failed to get user", err)
}
getAuthQuery := login.GetAuthInfoQuery{UserId: userID}
@ -104,9 +104,9 @@ func (hs *HTTPServer) GetUserByLoginOrEmail(c *contextmodel.ReqContext) response
usr, err := hs.userService.GetByLogin(c.Req.Context(), &query)
if err != nil {
if errors.Is(err, user.ErrUserNotFound) {
return response.Error(404, user.ErrUserNotFound.Error(), nil)
return response.Error(http.StatusNotFound, user.ErrUserNotFound.Error(), nil)
}
return response.Error(500, "Failed to get user", err)
return response.Error(http.StatusInternalServerError, "Failed to get user", err)
}
result := user.UserProfileDTO{
ID: usr.ID,
@ -203,13 +203,13 @@ func (hs *HTTPServer) UpdateUserActiveOrg(c *contextmodel.ReqContext) response.R
}
if !hs.validateUsingOrg(c.Req.Context(), userID, orgID) {
return response.Error(401, "Not a valid organization", nil)
return response.Error(http.StatusUnauthorized, "Not a valid organization", nil)
}
cmd := user.SetUsingOrgCommand{UserID: userID, OrgID: orgID}
if err := hs.userService.SetUsingOrg(c.Req.Context(), &cmd); err != nil {
return response.Error(500, "Failed to change active organization", err)
return response.Error(http.StatusInternalServerError, "Failed to change active organization", err)
}
return response.Success("Active organization changed")
@ -721,7 +721,7 @@ func (hs *HTTPServer) ClearHelpFlags(c *contextmodel.ReqContext) response.Respon
}
if err := hs.userService.SetUserHelpFlag(c.Req.Context(), &cmd); err != nil {
return response.Error(500, "Failed to update help flag", err)
return response.Error(http.StatusInternalServerError, "Failed to update help flag", err)
}
return response.JSON(http.StatusOK, &util.DynMap{"message": "Help flag set", "helpFlags1": cmd.HelpFlags1})

View File

@ -149,14 +149,14 @@ func (hs *HTTPServer) logoutUserFromAllDevicesInternal(ctx context.Context, user
_, err := hs.userService.GetByID(ctx, &userQuery)
if err != nil {
if errors.Is(err, user.ErrUserNotFound) {
return response.Error(404, "User not found", err)
return response.Error(http.StatusNotFound, "User not found", err)
}
return response.Error(500, "Could not read user from database", err)
return response.Error(http.StatusInternalServerError, "Could not read user from database", err)
}
err = hs.AuthTokenService.RevokeAllUserTokens(ctx, userID)
if err != nil {
return response.Error(500, "Failed to logout user", err)
return response.Error(http.StatusInternalServerError, "Failed to logout user", err)
}
return response.JSON(http.StatusOK, util.DynMap{
@ -181,7 +181,7 @@ func (hs *HTTPServer) getUserAuthTokensInternal(c *contextmodel.ReqContext, user
tokens, err := hs.AuthTokenService.GetUserTokens(c.Req.Context(), userID)
if err != nil {
return response.Error(500, "Failed to get user auth tokens", err)
return response.Error(http.StatusInternalServerError, "Failed to get user auth tokens", err)
}
result := []*dtos.UserToken{}
@ -241,29 +241,29 @@ func (hs *HTTPServer) revokeUserAuthTokenInternal(c *contextmodel.ReqContext, us
_, err := hs.userService.GetByID(c.Req.Context(), &userQuery)
if err != nil {
if errors.Is(err, user.ErrUserNotFound) {
return response.Error(404, "User not found", err)
return response.Error(http.StatusNotFound, "User not found", err)
}
return response.Error(500, "Failed to get user", err)
return response.Error(http.StatusInternalServerError, "Failed to get user", err)
}
token, err := hs.AuthTokenService.GetUserToken(c.Req.Context(), userID, cmd.AuthTokenId)
if err != nil {
if errors.Is(err, auth.ErrUserTokenNotFound) {
return response.Error(404, "User auth token not found", err)
return response.Error(http.StatusNotFound, "User auth token not found", err)
}
return response.Error(500, "Failed to get user auth token", err)
return response.Error(http.StatusInternalServerError, "Failed to get user auth token", err)
}
if c.UserToken != nil && c.UserToken.Id == token.Id {
return response.Error(400, "Cannot revoke active user auth token", nil)
return response.Error(http.StatusBadRequest, "Cannot revoke active user auth token", nil)
}
err = hs.AuthTokenService.RevokeToken(c.Req.Context(), token, false)
if err != nil {
if errors.Is(err, auth.ErrUserTokenNotFound) {
return response.Error(404, "User auth token not found", err)
return response.Error(http.StatusNotFound, "User auth token not found", err)
}
return response.Error(500, "Failed to revoke user auth token", err)
return response.Error(http.StatusInternalServerError, "Failed to revoke user auth token", err)
}
return response.JSON(http.StatusOK, util.DynMap{

View File

@ -56,7 +56,7 @@ func notAuthorized(c *contextmodel.ReqContext) {
func tokenRevoked(c *contextmodel.ReqContext, err *auth.TokenRevokedError) {
if c.IsApiRequest() {
c.JSON(401, map[string]any{
c.JSON(http.StatusUnauthorized, map[string]any{
"message": "Token revoked",
"error": map[string]any{
"id": "ERR_TOKEN_REVOKED",

View File

@ -170,9 +170,9 @@ func Recovery(cfg *setting.Cfg, license licensing.Licensing) web.Middleware {
resp["error"] = data.Title
}
ctx.JSON(500, resp)
ctx.JSON(http.StatusInternalServerError, resp)
} else {
ctx.HTML(500, cfg.ErrTemplateName, data)
ctx.HTML(http.StatusInternalServerError, cfg.ErrTemplateName, data)
}
}
}()

View File

@ -73,7 +73,7 @@ func (api *ImportDashboardAPI) ImportDashboard(c *contextmodel.ReqContext) respo
}
if limitReached {
return response.Error(403, "Quota reached", nil)
return response.Error(http.StatusForbidden, "Quota reached", nil)
}
req.User = c.SignedInUser

View File

@ -197,10 +197,10 @@ func (s *Service) PostSyncUserWithLDAP(c *contextmodel.ReqContext) response.Resp
authModuleQuery := &login.GetAuthInfoQuery{UserId: usr.ID, AuthModule: login.LDAPAuthModule}
if _, err := s.authInfoService.GetAuthInfo(c.Req.Context(), authModuleQuery); err != nil { // validate the userId comes from LDAP
if errors.Is(err, user.ErrUserNotFound) {
return response.Error(404, user.ErrUserNotFound.Error(), nil)
return response.Error(http.StatusNotFound, user.ErrUserNotFound.Error(), nil)
}
return response.Error(500, "Failed to get user", err)
return response.Error(http.StatusInternalServerError, "Failed to get user", err)
}
userInfo, _, err := ldapClient.User(usr.Login)

View File

@ -318,31 +318,31 @@ func (l *LibraryElementService) filterLibraryPanelsByPermission(c *contextmodel.
func toLibraryElementError(err error, message string) response.Response {
if errors.Is(err, model.ErrLibraryElementAlreadyExists) {
return response.Error(400, model.ErrLibraryElementAlreadyExists.Error(), err)
return response.Error(http.StatusBadRequest, model.ErrLibraryElementAlreadyExists.Error(), err)
}
if errors.Is(err, model.ErrLibraryElementNotFound) {
return response.Error(404, model.ErrLibraryElementNotFound.Error(), err)
return response.Error(http.StatusNotFound, model.ErrLibraryElementNotFound.Error(), err)
}
if errors.Is(err, model.ErrLibraryElementDashboardNotFound) {
return response.Error(404, model.ErrLibraryElementDashboardNotFound.Error(), err)
return response.Error(http.StatusNotFound, model.ErrLibraryElementDashboardNotFound.Error(), err)
}
if errors.Is(err, model.ErrLibraryElementVersionMismatch) {
return response.Error(412, model.ErrLibraryElementVersionMismatch.Error(), err)
return response.Error(http.StatusPreconditionFailed, model.ErrLibraryElementVersionMismatch.Error(), err)
}
if errors.Is(err, dashboards.ErrFolderNotFound) {
return response.Error(404, dashboards.ErrFolderNotFound.Error(), err)
return response.Error(http.StatusNotFound, dashboards.ErrFolderNotFound.Error(), err)
}
if errors.Is(err, dashboards.ErrFolderAccessDenied) {
return response.Error(403, dashboards.ErrFolderAccessDenied.Error(), err)
return response.Error(http.StatusForbidden, dashboards.ErrFolderAccessDenied.Error(), err)
}
if errors.Is(err, model.ErrLibraryElementHasConnections) {
return response.Error(403, model.ErrLibraryElementHasConnections.Error(), err)
return response.Error(http.StatusForbidden, model.ErrLibraryElementHasConnections.Error(), err)
}
if errors.Is(err, model.ErrLibraryElementInvalidUID) {
return response.Error(400, model.ErrLibraryElementInvalidUID.Error(), err)
return response.Error(http.StatusBadRequest, model.ErrLibraryElementInvalidUID.Error(), err)
}
if errors.Is(err, model.ErrLibraryElementUIDTooLong) {
return response.Error(400, model.ErrLibraryElementUIDTooLong.Error(), err)
return response.Error(http.StatusBadRequest, model.ErrLibraryElementUIDTooLong.Error(), err)
}
return response.ErrOrFallback(http.StatusInternalServerError, message, err)
}

View File

@ -1043,7 +1043,7 @@ func (g *GrafanaLive) HandleInfoHTTP(ctx *contextmodel.ReqContext) response.Resp
"active": g.GrafanaScope.Dashboards.HasGitOpsObserver(ctx.SignedInUser.GetOrgID()),
})
}
return response.JSONStreaming(404, util.DynMap{
return response.JSONStreaming(http.StatusNotFound, util.DynMap{
"message": "Info is not supported for this channel",
})
}

View File

@ -72,16 +72,16 @@ func (srv ConfigSrv) RoutePostNGalertConfig(c *contextmodel.ReqContext, body api
sendAlertsTo, err := ngmodels.StringToAlertmanagersChoice(string(body.AlertmanagersChoice))
if err != nil {
return response.Error(400, "Invalid alertmanager choice specified", err)
return response.Error(http.StatusBadRequest, "Invalid alertmanager choice specified", err)
}
externalAlertmanagers, err := srv.externalAlertmanagers(c.Req.Context(), c.SignedInUser.GetOrgID())
if err != nil {
return response.Error(500, "Couldn't fetch the external Alertmanagers from datasources", err)
return response.Error(http.StatusInternalServerError, "Couldn't fetch the external Alertmanagers from datasources", err)
}
if sendAlertsTo == ngmodels.ExternalAlertmanagers && len(externalAlertmanagers) < 1 {
return response.Error(400, "At least one Alertmanager must be provided or configured as a datasource that handles alerts to choose this option", nil)
return response.Error(http.StatusBadRequest, "At least one Alertmanager must be provided or configured as a datasource that handles alerts to choose this option", nil)
}
cfg := &ngmodels.AdminConfiguration{

View File

@ -604,11 +604,11 @@ func exportHcl(download bool, body definitions.AlertingFileExport) response.Resp
return nil
}
if err := convertToResources(); err != nil {
return response.Error(500, "failed to convert to HCL resources", err)
return response.Error(http.StatusInternalServerError, "failed to convert to HCL resources", err)
}
hclBody, err := hcl.Encode(resources...)
if err != nil {
return response.Error(500, "body hcl encode", err)
return response.Error(http.StatusInternalServerError, "body hcl encode", err)
}
resp := response.Respond(http.StatusOK, hclBody)
if download {

View File

@ -4,6 +4,7 @@ import (
"encoding/json"
"errors"
"io"
"net/http"
"github.com/prometheus/client_golang/prometheus"
@ -39,7 +40,7 @@ func (s *searchHTTPService) doQuery(c *contextmodel.ReqContext) response.Respons
"reason": searchReadinessCheckResp.Reason,
}).Inc()
return response.JSON(200, &backend.DataResponse{
return response.JSON(http.StatusOK, &backend.DataResponse{
Frames: []*data.Frame{{
Name: "Loading",
}},
@ -49,30 +50,30 @@ func (s *searchHTTPService) doQuery(c *contextmodel.ReqContext) response.Respons
body, err := io.ReadAll(c.Req.Body)
if err != nil {
return response.Error(500, "error reading bytes", err)
return response.Error(http.StatusInternalServerError, "error reading bytes", err)
}
query := &DashboardQuery{}
err = json.Unmarshal(body, query)
if err != nil {
return response.Error(400, "error parsing body", err)
return response.Error(http.StatusBadRequest, "error parsing body", err)
}
resp := s.search.doDashboardQuery(c.Req.Context(), c.SignedInUser, c.SignedInUser.GetOrgID(), *query)
if resp.Error != nil {
return response.Error(500, "error handling search request", resp.Error)
return response.Error(http.StatusInternalServerError, "error handling search request", resp.Error)
}
if len(resp.Frames) == 0 {
msg := "invalid search response"
return response.Error(500, msg, errors.New(msg))
return response.Error(http.StatusInternalServerError, msg, errors.New(msg))
}
bytes, err := resp.MarshalJSON()
if err != nil {
return response.Error(500, "error marshalling response", err)
return response.Error(http.StatusInternalServerError, "error marshalling response", err)
}
return response.JSON(200, bytes)
return response.JSON(http.StatusOK, bytes)
}

View File

@ -46,7 +46,7 @@ func ProvideUsersService(cfg *setting.Cfg, searchUserFilter user.SearchUserFilte
func (s *OSSService) SearchUsers(c *contextmodel.ReqContext) response.Response {
result, err := s.SearchUser(c)
if err != nil {
return response.ErrOrFallback(500, "Failed to fetch users", err)
return response.ErrOrFallback(http.StatusInternalServerError, "Failed to fetch users", err)
}
return response.JSON(http.StatusOK, result.Users)
@ -65,7 +65,7 @@ func (s *OSSService) SearchUsers(c *contextmodel.ReqContext) response.Response {
func (s *OSSService) SearchUsersWithPaging(c *contextmodel.ReqContext) response.Response {
result, err := s.SearchUser(c)
if err != nil {
return response.ErrOrFallback(500, "Failed to fetch users", err)
return response.ErrOrFallback(http.StatusInternalServerError, "Failed to fetch users", err)
}
return response.JSON(http.StatusOK, result)

View File

@ -68,7 +68,7 @@ func (s *standardStorageService) doWrite(c *contextmodel.ReqContext) response.Re
if err != nil {
return response.Error(http.StatusBadRequest, "save error", err)
}
return response.JSON(200, rsp)
return response.JSON(http.StatusOK, rsp)
}
func (s *standardStorageService) doUpload(c *contextmodel.ReqContext) response.Response {
@ -85,7 +85,7 @@ func (s *standardStorageService) doUpload(c *contextmodel.ReqContext) response.R
if err := c.Req.ParseMultipartForm(MAX_UPLOAD_SIZE); err != nil {
rsp.Message = fmt.Sprintf("Please limit file uploaded under %s", util.ByteCountSI(MAX_UPLOAD_SIZE))
rsp.Error = true
return response.JSON(400, rsp)
return response.JSON(http.StatusBadRequest, rsp)
}
message := getMultipartFormValue(c.Req, "message")
overwriteExistingFile := getMultipartFormValue(c.Req, "overwriteExistingFile") != "false" // must explicitly overwrite
@ -99,7 +99,7 @@ func (s *standardStorageService) doUpload(c *contextmodel.ReqContext) response.R
if path == "" && folder == "" {
rsp.Message = "please specify the upload folder or full path"
rsp.Error = true
return response.JSON(400, rsp)
return response.JSON(http.StatusBadRequest, rsp)
}
for _, fileHeader := range fileHeaders {
@ -107,15 +107,15 @@ func (s *standardStorageService) doUpload(c *contextmodel.ReqContext) response.R
// open each file to copy contents
file, err := fileHeader.Open()
if err != nil {
return response.Error(500, "Internal Server Error", err)
return response.Error(http.StatusInternalServerError, "Internal Server Error", err)
}
err = file.Close()
if err != nil {
return response.Error(500, "Internal Server Error", err)
return response.Error(http.StatusInternalServerError, "Internal Server Error", err)
}
data, err := io.ReadAll(file)
if err != nil {
return response.Error(500, "Internal Server Error", err)
return response.Error(http.StatusInternalServerError, "Internal Server Error", err)
}
if path == "" {
@ -147,7 +147,7 @@ func (s *standardStorageService) doUpload(c *contextmodel.ReqContext) response.R
}
}
return response.JSON(200, rsp)
return response.JSON(http.StatusOK, rsp)
}
func getMultipartFormValue(req *http.Request, key string) string {
@ -163,11 +163,11 @@ func (s *standardStorageService) read(c *contextmodel.ReqContext) response.Respo
scope, path := getPathAndScope(c)
file, err := s.Read(c.Req.Context(), c.SignedInUser, scope+"/"+path)
if err != nil {
return response.Error(400, "cannot call read", err)
return response.Error(http.StatusBadRequest, "cannot call read", err)
}
if file == nil || file.Contents == nil {
return response.Error(404, "file does not exist", err)
return response.Error(http.StatusNotFound, "file does not exist", err)
}
// set the correct content type for svg
@ -181,9 +181,9 @@ func (s *standardStorageService) getOptions(c *contextmodel.ReqContext) response
scope, path := getPathAndScope(c)
opts, err := s.getWorkflowOptions(c.Req.Context(), c.SignedInUser, scope+"/"+path)
if err != nil {
return response.Error(400, err.Error(), err)
return response.Error(http.StatusBadRequest, err.Error(), err)
}
return response.JSON(200, opts)
return response.JSON(http.StatusOK, opts)
}
func (s *standardStorageService) doDelete(c *contextmodel.ReqContext) response.Response {
@ -192,9 +192,9 @@ func (s *standardStorageService) doDelete(c *contextmodel.ReqContext) response.R
err := s.Delete(c.Req.Context(), c.SignedInUser, scope+"/"+path)
if err != nil {
return response.Error(400, "failed to delete the file: "+err.Error(), err)
return response.Error(http.StatusBadRequest, "failed to delete the file: "+err.Error(), err)
}
return response.JSON(200, map[string]any{
return response.JSON(http.StatusOK, map[string]any{
"message": "Removed file from storage",
"success": true,
"path": path,
@ -204,26 +204,26 @@ func (s *standardStorageService) doDelete(c *contextmodel.ReqContext) response.R
func (s *standardStorageService) doDeleteFolder(c *contextmodel.ReqContext) response.Response {
body, err := io.ReadAll(c.Req.Body)
if err != nil {
return response.Error(500, "error reading bytes", err)
return response.Error(http.StatusInternalServerError, "error reading bytes", err)
}
cmd := &DeleteFolderCmd{}
err = json.Unmarshal(body, cmd)
if err != nil {
return response.Error(400, "error parsing body", err)
return response.Error(http.StatusBadRequest, "error parsing body", err)
}
if cmd.Path == "" {
return response.Error(400, "empty path", err)
return response.Error(http.StatusBadRequest, "empty path", err)
}
// full path is api/storage/delete/upload/example.jpg, but we only want the part after upload
_, path := getPathAndScope(c)
if err := s.DeleteFolder(c.Req.Context(), c.SignedInUser, cmd); err != nil {
return response.Error(400, "failed to delete the folder: "+err.Error(), err)
return response.Error(http.StatusBadRequest, "failed to delete the folder: "+err.Error(), err)
}
return response.JSON(200, map[string]any{
return response.JSON(http.StatusOK, map[string]any{
"message": "Removed folder from storage",
"success": true,
"path": path,
@ -233,24 +233,24 @@ func (s *standardStorageService) doDeleteFolder(c *contextmodel.ReqContext) resp
func (s *standardStorageService) doCreateFolder(c *contextmodel.ReqContext) response.Response {
body, err := io.ReadAll(c.Req.Body)
if err != nil {
return response.Error(500, "error reading bytes", err)
return response.Error(http.StatusInternalServerError, "error reading bytes", err)
}
cmd := &CreateFolderCmd{}
err = json.Unmarshal(body, cmd)
if err != nil {
return response.Error(400, "error parsing body", err)
return response.Error(http.StatusBadRequest, "error parsing body", err)
}
if cmd.Path == "" {
return response.Error(400, "empty path", err)
return response.Error(http.StatusBadRequest, "empty path", err)
}
if err := s.CreateFolder(c.Req.Context(), c.SignedInUser, cmd); err != nil {
return response.Error(400, "failed to create the folder: "+err.Error(), err)
return response.Error(http.StatusBadRequest, "failed to create the folder: "+err.Error(), err)
}
return response.JSON(200, map[string]any{
return response.JSON(http.StatusOK, map[string]any{
"message": "Folder created",
"success": true,
"path": cmd.Path,
@ -263,10 +263,10 @@ func (s *standardStorageService) list(c *contextmodel.ReqContext) response.Respo
// maxFiles of 0 will result in default behaviour from wrapper
frame, err := s.List(c.Req.Context(), c.SignedInUser, path, 0)
if err != nil {
return response.Error(400, "error reading path", err)
return response.Error(http.StatusBadRequest, "error reading path", err)
}
if frame == nil {
return response.Error(404, "not found", nil)
return response.Error(http.StatusNotFound, "not found", nil)
}
return response.JSONStreaming(http.StatusOK, frame)
}
@ -281,5 +281,5 @@ func (s *standardStorageService) getConfig(c *contextmodel.ReqContext) response.
for _, s := range storages {
roots = append(roots, s.Meta())
}
return response.JSON(200, roots)
return response.JSON(http.StatusOK, roots)
}