"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > 미들웨어 접근 방식을 사용하여 Gin 웹 애플리케이션 내 오류를 효과적으로 처리하려면 어떻게 해야 합니까?

미들웨어 접근 방식을 사용하여 Gin 웹 애플리케이션 내 오류를 효과적으로 처리하려면 어떻게 해야 합니까?

2024-11-07에 게시됨
검색:876

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