In a recent discussion, a technique was proposed to enhance error handling in Golang HTTP applications using custom routers and error types. The goal was to centralize error reporting and handling, eliminating the need for direct calls to c.JSON(500, err) within specific handlers.
In the Gin framework, this can be achieved through the use of a middleware and the gin.Context.Error() method. Here's how it works:
<code class="go">type AppError struct { Code int `json:"code"` Message string `json:"message"` } func JSONAppErrorReporter(errType gin.ErrorType) gin.HandlerFunc { return func(c *gin.Context) { c.Next() errors := c.Errors.ByType(errType) if len(errors) > 0 { err := errors[0].Err var parsedError *AppError switch err.(type) { case *AppError: parsedError = err.(*AppError) default: parsedError = &AppError{ code: http.StatusInternalServerError, message: "Internal Server Error", } } c.IndentedJSON(parsedError.Code, parsedError) c.Abort() } } }</code>
<code class="go">router.Use(JSONAppErrorReporter(gin.ErrorTypeAny))</code>
<code class="go">func fetchSingleHostGroup(c *gin.Context) { hostgroupID := c.Param("id") hostGroupRes, err := getHostGroupResource(hostgroupID) if err != nil { c.Error(err) return } c.JSON(http.StatusOK, *hostGroupRes) }</code>
<code class="go">router := gin.Default() router.GET("/hostgroups/:id", fetchSingleHostGroup) router.Run(":3000")</code>
For further information on error handling in Gin, refer to these resources:
The above is the detailed content of How to Implement Centralized Error Handling in the Gin Framework?. For more information, please follow other related articles on the PHP Chinese website!