The ginerr package provides a simple and effective way to manage errors in your Gin applications. It defines a consistent error structure and includes middleware to automatically handle and return errors to clients in a standardized format.
- Standardized Error Structure: Defines a
HighLevelErrortype that wraps HTTP status codes and error messages. - Common Error Definitions: Provides predefined instances of
HighLevelErrorfor common HTTP status codes. - Gin Middleware: Includes a
GinErrorHandlerMiddlewareto automatically handle and format errors thrown in Gin routes. - Convenience Functions: Provides a simple
AbortAndErrorfunction to gracefully handle errors and abort requests. - Error Extraction: The
ExtractErrorfunction can be used to extractHighLevelErrorfrom any error.
Use the following command to install the package:
go get github.com/vloldik/ginerr-
Import the Package:
import ( "github.com/vloldik/ginerr" "github.com/gin-gonic/gin" )
-
Create and Use Errors:
func handleRequest(c *gin.Context) { // ... your logic if err := someError(); err != nil { ginerr.AbortAndError(c, ginerr.NewHighLevelError(http.StatusInternalServerError, "Something went wrong")) return } // ... }
-
Use Predefined Errors:
func handleRequest(c *gin.Context) { // ... your logic if err := someError(); err != nil { ginerr.AbortAndError(c, ginerr.InternalServerError) return } // ... }
-
Use Error Extraction for Custom Errors:
func handleRequest(c *gin.Context) { // ... your logic if err := someError(); err != nil { highLevelErr := ginerr.ExtractError(err) ginerr.AbortAndError(c, highLevelErr) return } // ... }
-
Use Middleware:
func main() { r := gin.Default() // ... your route setup // Register the middleware r.Use(ginerr.GinErrorHandlerMiddleware) // ... your route setup r.Run() }
package main
import (
"github.com/vloldik/ginerr"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.Use(ginerr.GinErrorHandlerMiddleware)
r.GET("/users/:id", func(c *gin.Context) {
id := c.Param("id")
// ... logic to fetch user by ID
if id == "invalid" {
ginerr.AbortAndError(c, ginerr.NotFound)
return
}
// ... Handle success
})
r.Run()
}HighLevelError
type HighLevelError struct {
Code int
Message string
}Represents a standardized error with an HTTP status code and an error message.
Predefined Errors:
- DefaultInternalError:
http.StatusInternalServerError, "internal server error" - BadRequest:
http.StatusBadRequest, "missed parameter, incorrect or malformed data" - NotFound:
http.StatusNotFound, "not found" - Unauthorized:
http.StatusUnauthorized, "unauthorized" - Forbidden:
http.StatusForbidden, "forbidden" - Conflict:
http.StatusConflict, "conflict" - TooManyRequests:
http.StatusTooManyRequests, "too many requests" - InternalServerError:
http.StatusInternalServerError, "internal server error" - NotImplemented:
http.StatusNotImplemented, "not implemented" - ServiceUnavailable:
http.StatusServiceUnavailable, "service unavailable" - GatewayTimeout:
http.StatusGatewayTimeout, "gateway timeout" - BadGateway:
http.StatusBadGateway, "bad gateway" - ProxyError:
http.StatusBadGateway, "proxy error" - UnknownError:
http.StatusInternalServerError, "unknown error"
ExtractError:
func ExtractError(err error) HighLevelErrorExtracts a HighLevelError from any error, returning DefaultInternalError if no HighLevelError is found.
GinErrorHandlerMiddleware:
func GinErrorHandlerMiddleware(context *gin.Context)Middleware that automatically handles errors thrown in Gin routes. It extracts the HighLevelError and returns a JSON response to the client.
AbortAndError:
func AbortAndError(c *gin.Context, err error)Aborts the request and sets the error to be handled by the GinErrorHandlerMiddleware.
Contributions are welcome! Please feel free to open issues or submit pull requests.
The ginerr package is released under the MIT license.