handler

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 7, 2024 License: AGPL-3.0 Imports: 3 Imported by: 0

README

Gin Error Handler

A Gin middleware and wrapper functions to make handling errors easier.

Installation

Use the module in the usual way: codeberg.org/danjones000/gin-error-handler.

Usage

package main

import (
    "net/http"
    handler "codeberg.org/danjones000/gin-error-handler"
    rErrors "codeberg.org/danjones000/responsable-errors"
    "github.com/go-playground/validator/v10"
    "github.com/gin-gonic/gin"
)

var _ rErrors.ResponsableError = new(vError)

type vError struct {
    validator.ValidationErrors
}

func (ve *vError) Msg() string {
    return "Validation Error"
}

func (ve *vError) Status() int {
    return http.StatusBadRequest
}

func (ve *vError) JSON() any {
    errs := make([]map[string]string, len(ve))
    for i, fe := range ve {
        errs[i] = map[string]string{"field":fe.Field(),"error":fe.Error()}
    }
    return map[string][]map[string]string{"errors":errs}
}

func (ve *vError) MarshalJSON() ([]byte, error) {
	return json.Marshal(e.JSON())
}

func (ve *vError) Unwrap() error {
	return ve.ValidationErrors
}

func main() {
    r := gin.New()
    r.Use(handler.ErrorMiddleware(
        handler.WithTransformer(func (err error) rErrors.ResponsableError {
            var ve validator.ValidationErrors
            if !errors.As(err, &ve) {
                return nil
            }
            return &vError{ve}
        }),
        handler.WithDefaultTransformer(),
        handler.WithLogger(ctx context.Context, err rErrors.ResponsableError) {
            log.Print(err)
        })

    r.GET("/user", handler.HandlerWithErrorWrapper(func (c *gin.Context) error {
        var qu struct {
            id int `binding:"required"`
        }{}
        if err := c.ShouldBindQuery(&qu); err != nil {
            return err
        }
        user, err := user.Get(qu.id)
        if err != nil {
            return err
        }
        if user == nil {
            return rErrors.NewNotFound("User not found")
        }

        c.JSON(200, user)
    }))
}

In our example, if ShouldBindQuery fails validation, we'll return a nicely formatted error with each validation error, due to our custom transformer. If no user is found, we'll return a 404, with an error message. And any errors are logged to stdout.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ErrorMiddleware

func ErrorMiddleware(opts ...Option) gin.HandlerFunc

Returns a gin middleware which writes a response with the error in the context.

func HandlerWithErrorWrapper

func HandlerWithErrorWrapper(h HandlerWithError) gin.HandlerFunc

Allows you to actually use a HandlerWithError as a gin.HandlerFunc. If an error is returned, it adds it to the context with c.Error(err). This needs to be handled with a middleware, such as ErrorMiddleware

Usage:

c.GET("/user", HandlerWithErrorWrapper(UserHandler))

Types

type HandlerWithError

type HandlerWithError func(c *gin.Context) error

This is essentially the same as gin.HandlerFunc, but allows returning an error. This allows for the more idiomatic use:

func UserHandler (c *gin.Context) error {
    user, err := db.GetUser(c.Get("user"))
    if err != nil {
        return err
    }
    c.JSON(200, user)
}

type LoggerFunc

type LoggerFunc func(*gin.Context, rErrors.ResponsableError)

A function which should be used to log the responded error.

type Option

type Option func(config) config

An option that customizes the behavior of ErrorMiddleware

func WithDefaultTransformer

func WithDefaultTransformer() Option

Provides an Option which adds the default Transformer to the ErrorMiddleware

This Transformer handles a gin.Error.

func WithLogger

func WithLogger(logger LoggerFunc) Option

Provides an Option which adds the specified LoggerFunc to the ErrorMiddleware

Multiple LoggerFunc may be added.

func WithTransformer

func WithTransformer(tr Transformer) Option

Provides an Option which adds the specified Transformer to the ErrorMiddleware

Multiple Transformer may (and probably should) be added.

type Transformer

type Transformer func(error) rErrors.ResponsableError

A function which should potentially return a rErrors.ResponsableError which wraps the provided error.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL