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의 오류 처리에 대한 자세한 내용은 다음 리소스를 참조하세요.
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3