github.com/kuoss/venti@v0.2.20/pkg/handler/api/error.go (about) 1 package api 2 3 import ( 4 "net/http" 5 6 "github.com/gin-gonic/gin" 7 ) 8 9 func ResponseError(c *gin.Context, typ errorType, err error) { 10 // https://prometheus.io/docs/prometheus/latest/querying/api/#format-overview 11 c.JSON(getCodeFromType(typ), gin.H{ 12 "status": "error", 13 "errorType": typ, 14 "error": err.Error(), 15 }) 16 } 17 18 // https://github.com/prometheus/prometheus/blob/main/web/api/v1/api.go#L72 19 type errorType string 20 21 const ( 22 ErrorCanceled errorType = "canceled" // 23 ErrorExec errorType = "execution" // 24 ErrorUnauthorized errorType = "unauthorized" // 401 Unauthorized 25 ErrorNotFound errorType = "not_found" // 404 Not Found 26 ErrorBadData errorType = "bad_data" // 405 StatusMethodNotAllowed 27 ErrorTimeout errorType = "timeout" // 408 Request Timeout 28 ErrorInternal errorType = "internal" // 500 Internal Server Error 29 ErrorUnavailable errorType = "unavailable" // 503 Service Unavailable 30 ) 31 32 type Error struct { 33 Type errorType 34 Err error 35 } 36 37 func getCodeFromType(typ errorType) int { 38 switch typ { 39 case ErrorUnauthorized: 40 return http.StatusUnauthorized // 401 Unauthorized 41 case ErrorNotFound: 42 return http.StatusNotFound // 404 Not Found 43 case ErrorBadData: 44 return http.StatusMethodNotAllowed // 405 StatusMethodNotAllowed 45 case ErrorTimeout: 46 return http.StatusRequestTimeout // 408 Request Timeout 47 case ErrorInternal: 48 return http.StatusInternalServerError // 500 Internal Server Error 49 case ErrorUnavailable: 50 return http.StatusServiceUnavailable // 503 Service Unavailable 51 } 52 return http.StatusServiceUnavailable // 503 Service Unavailable 53 }