61 lines
		
	
	
	
		
			1.1 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			61 lines
		
	
	
	
		
			1.1 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
| package handler
 | |
| 
 | |
| import (
 | |
| 	"errors"
 | |
| 
 | |
| 	rErrors "codeberg.org/danjones000/responsable-errors"
 | |
| 	"github.com/gin-gonic/gin"
 | |
| )
 | |
| 
 | |
| // Returns a gin middleware which writes a response with the error in the context.
 | |
| func ErrorMiddleware(opts ...Option) gin.HandlerFunc {
 | |
| 	conf := config{}
 | |
| 	for _, opt := range opts {
 | |
| 		conf = opt(conf)
 | |
| 	}
 | |
| 
 | |
| 	if len(conf.transformers) == 0 {
 | |
| 		conf.transformers = []Transformer{ginTransformer}
 | |
| 	}
 | |
| 
 | |
| 	return func(c *gin.Context) {
 | |
| 		c.Next()
 | |
| 		err := c.Errors.Last()
 | |
| 		if err == nil {
 | |
| 			return
 | |
| 		}
 | |
| 
 | |
| 		var re rErrors.ResponsableError
 | |
| 
 | |
| 		errors.As(err, &re)
 | |
| 		// If we have at least one that's a ResponsableError, we should use it
 | |
| 		for _, err = range c.Errors {
 | |
| 			if re != nil {
 | |
| 				break
 | |
| 			}
 | |
| 			errors.As(err, &re)
 | |
| 		}
 | |
| 
 | |
| 		// Next, let's check our transformers
 | |
| 		for _, trans := range conf.transformers {
 | |
| 			if re != nil {
 | |
| 				break
 | |
| 			}
 | |
| 			re = trans(err)
 | |
| 		}
 | |
| 
 | |
| 		// Still couldn't find one, so it's a 500
 | |
| 		if re == nil {
 | |
| 			re = rErrors.NewInternalError("%w", err)
 | |
| 		}
 | |
| 
 | |
| 		for _, logger := range conf.loggers {
 | |
| 			logger(c, re)
 | |
| 		}
 | |
| 
 | |
| 		c.Set("rendered_error", re)
 | |
| 
 | |
| 		// @todo check a response hasn't already been sent
 | |
| 		c.JSON(re.Status(), re)
 | |
| 	}
 | |
| }
 |