From d78018c5d132c6a34580f0656946bbbb179c1d46 Mon Sep 17 00:00:00 2001 From: fabiante <7669818+fabiante@users.noreply.github.com> Date: Sun, 20 Oct 2024 10:16:23 +0000 Subject: [PATCH 1/2] Add custom err handler --- api/err.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/api/err.go b/api/err.go index d378f1a..7f7c25c 100644 --- a/api/err.go +++ b/api/err.go @@ -14,3 +14,16 @@ func respondWithError(ctx *gin.Context, status int, err error) { ctx.AbortWithStatusJSON(status, response) } + +type ErrHandler func(c *gin.Context) error + +func AsErrHandler(h ErrHandler) gin.HandlerFunc { + return func(ctx *gin.Context) { + err := h(ctx) + + if err != nil { + _ = ctx.AbortWithError(500, err) + return + } + } +} From c1463cb4be44ff24073ad5229cfc73ddd9cf8ae7 Mon Sep 17 00:00:00 2001 From: fabiante <7669818+fabiante@users.noreply.github.com> Date: Sun, 20 Oct 2024 10:20:27 +0000 Subject: [PATCH 2/2] Use custom err handler --- api/server.go | 8 ++++---- api/server_routes.go | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/api/server.go b/api/server.go index 2315ca0..3a764dc 100644 --- a/api/server.go +++ b/api/server.go @@ -18,7 +18,7 @@ func NewServer(resolver app.ResolveServiceInterface, admin app.AdminServiceInter return &Server{resolver: resolver, admin: admin, user: user} } -func (s *Server) Resolve(ctx *gin.Context) { +func (s *Server) Resolve(ctx *gin.Context) error { domain := ctx.Param("domain") name := ctx.Param("name") @@ -26,11 +26,11 @@ func (s *Server) Resolve(ctx *gin.Context) { switch true { case err == nil: ctx.Redirect(http.StatusFound, target) - return + return nil case errors.Is(err, app.ErrNotFound): respondWithError(ctx, http.StatusNotFound, err) - return + return nil default: - respondWithError(ctx, http.StatusInternalServerError, err) + return err } } diff --git a/api/server_routes.go b/api/server_routes.go index c0524db..4280007 100644 --- a/api/server_routes.go +++ b/api/server_routes.go @@ -30,7 +30,7 @@ func SetupRouting(r gin.IRouter, s *Server) { resolve.Use(validDomain, validName) - resolve.GET("/:domain/:name", s.Resolve) + resolve.GET("/:domain/:name", AsErrHandler(s.Resolve)) } // Admin endpoints