」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何使用中間件方法有效處理 Gin Web 應用程式中的錯誤?

如何使用中間件方法有效處理 Gin Web 應用程式中的錯誤?

發佈於2024-11-07
瀏覽:619

How can I effectively handle errors within my Gin web application using a middleware approach?

增強 Gin 中的錯誤處理

Gin 的自訂錯誤處理涉及使用中間件來處理錯誤回應。這允許錯誤邏輯與正常流程邏輯分離。

錯誤處理中介軟體

type appError struct {
    Code    int
    Message string
}

func JSONAppErrorReporter() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Next()
        errors := c.Errors.ByType(gin.ErrorTypeAny)

        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",
                }
            }
            // Respond with JSON serialized error
            c.IndentedJSON(parsedError.Code, parsedError)
            c.Abort()
        }
    }
}

處理函數中的用法

func fetchSingleHostGroup(c *gin.Context) {
    hostgroupID := c.Param("id")

    hostGroupRes, err := getHostGroupResource(hostgroupID)

    if err != nil {
        // Attach error to the context
        c.Error(err)
        return
    }

    // Respond with valid data
    c.JSON(http.StatusOK, *hostGroupRes)
}

伺服器設定

func main() {
    router := gin.Default()
    router.Use(JSONAppErrorReporter())
    router.GET("/hostgroups/:id", fetchSingleHostGroup)
    router.Run(":3000")
}

其他資源

要進一步了解 Gin 中的錯誤處理,請參閱以下資源:

  • [gin-gonic問題#327](https://github.com/gin-gonic/gin/issues/327)
  • [gin-gonic問題#651](https://github.com/gin-gonic/ gin /issues/651)
  • [chirp](https://github.com/go-chi/chi/tree/master/middleware)
  • [gin-merry](https:/ /github.com/gin-contrib/gin-merry)
  • [gin-frsh-showerrors](https://github.com/frsh/gin-showerrors)
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3