Gin-errorhandling - Gin Error Handling Middleware is a middleware for the popular Gin framework

Gin Error Handling Middleware

Gin Error Handling Middleware is a middleware for the popular Gin framework that enables you to configure error handling centrally as a convention within your Go application, as opposed to explicitly handling exceptions within each handler or controller action.

This gives the following benefits:

  • Centralised location for handling errors
  • Reduce boilerplate 'error to response' mappings in your request handlers/controller actions
  • Helps protect yourself from inadvertently revealing errors to API consumers

Quick Start

Mapping to a status code

var (
    NotFoundError = fmt.Errorf("resource could not be found")
)

func main() {
    r := gin.Default()
    r.Use(
        ErrorHandler(
            Map(NotFoundError).ToStatusCode(http.StatusNotFound),
        ))

    r.GET("/ping", func(c *gin.Context) {
        c.Error(NotFoundError)
    })

    r.Run()
}

Returns the following HTTP response:

HTTP/1.1 404 Not Found
Date: Wed, 16 Feb 2022 04:08:50 GMT
Content-Length: 0
Connection: close

Mapping to the response

var (
    NotFoundError = fmt.Errorf("resource could not be found")
)

func main() {
    r := gin.Default()
    r.Use(
        ErrorHandler(
            Map(NotFoundError).ToResponse(func(c *gin.Context, err error) {
                c.Status(http.StatusNotFound)
                c.Writer.Write([]byte(err.Error())),
            }),
        ))

    r.GET("/ping", func(c *gin.Context) {
        c.Error(NotFoundError)
    })

    r.Run()
}

Returns the following response:

HTTP/1.1 404 Not Found
Date: Wed, 16 Feb 2022 04:21:37 GMT
Content-Length: 27
Content-Type: text/plain; charset=utf-8
Connection: close

resource could not be found
Owner
Joseph Woodward
Senior Engineer at @form3tech-oss, Go lover, organiser of .NET South West, co-organiser of DDD South West, speaker, blogger. Loves sharing knowledge, learning,
Joseph Woodward
Similar Resources

Simple web app using Go and Gin framework

go-gin-app Simple web app using Go and Gin framework Golang 과 Gin 프레임워크를 사용한 간단한 웹 앱 How to get Started Install Gin and have Go installed on your syst

Oct 18, 2021

A fully functional Ecommerce API in GO GIN Framework and mongoDB with JWT Authentication

A fully functional Ecommerce API in GO GIN Framework and mongoDB  with JWT Authentication

Fully functional ECOMMERCE API USING GIN FRAMEWORK AND MONGODB -----Initial Release v2.30 ⚠️ Not tested the efficiency project structure Ecommerce 📁

Dec 11, 2022

Menggunakan gol ver 1.13.15 dan framework gin dan gorm

Menggunakan gol ver 1.13.15 dan framework gin dan gorm

Jul 11, 2022

Restful API example with using go and gin framework

simple device api Simple Device API is really simple and concise to show how easy to implement a Restful Service with using Golang. It uses gin framew

Nov 18, 2021

A simple blog based on gin framework

gin-blog 介绍 a simple blog based on gin framework 软件架构 MySQL/MariaDB as database 安装教程 基于Docker启动MySQL/MariaDB 使用说明 启动MySQL in Docker. 参与贡献 Fork 本仓库 新建

Nov 15, 2021

Simple control panel for Golang based on Gin framework and MongoDB

Simple control panel for Golang based on Gin framework and MongoDB

Summer panel Simple control panel for Golang based on Gin framework and MongoDB How To Install go install github.com/night-codes/summer/summerGen@late

Dec 16, 2022

Golang Gin Framework Fundamental

Golang Gin Framework Fundamental Example golang using gin framework everything you need, i create this tutorial special for beginner. Feature Containe

Nov 9, 2022

REST API for a shoe store using Go and Gin Web Framework

REST API for a shoe store using Go and Gin Web Framework This API uses a local PostgreSQL database that's set through the /gopostgres/driverConfig.go

Dec 26, 2021

Using golang framework (Gin) to create a web-application

News feeder Using golang framework (Gin) to create a web-application. This simpl

Aug 22, 2022
Comments
  • Package naming is incorrect

    Package naming is incorrect

    This looks pretty neat but your package name is incorrect. So it can't be easily imported without modification. package name should be github.com/JosephWoodward/ginerrorhandling.

    Note that packages with a - don't work either: https://go.dev/blog/package-names

    you can see the issue by just running: go get github.com/JosephWoodward/gin-errorhandling

Gin-boilerplate - This repository contains boilerplate code of a REST service using Gin (golang) framework.

Boilerplate REST service using Gin web framework (golang) Introduction This repository contains a boilerplate REST API service using Gin web framework

Apr 28, 2022
GoCondor is a golang web framework with an MVC like architecture, it's based on Gin framework
GoCondor is a golang web framework with an MVC like architecture, it's based on Gin framework

GoCondor is a golang web framework with an MVC like architecture, it's based on Gin framework, it features a simple organized directory structure for your next project with a pleasant development experience, made for developing modern APIs and microservices.

Dec 29, 2022
GoTrue is a small open-source API written in Golang, that can act as a self-standing API service for handling user registration and authentication for Jamstack projects.
GoTrue is a small open-source API written in Golang, that can act as a self-standing API service for handling user registration and authentication for Jamstack projects.

GoTrue is a small open-source API written in Golang, that can act as a self-standing API service for handling user registration and authentication for Jamstack projects.

Dec 13, 2021
Gin-easy-todo - golang 의 RESTful API 프레임워크 gin 을 활용해 아주 간단한 Todo 애플리케이션을 만들어보자.
Gin-easy-todo - golang 의 RESTful API 프레임워크 gin 을 활용해 아주 간단한 Todo 애플리케이션을 만들어보자.

목차 1. 요약 2. 목표 3. API 목록 4. 프로젝트 구조 5. 패키지 별 기능과 관계 6. 사전 작업 6.1. DB, Table 생성 6.2. 모듈 생성 6.3. 패키지 다운로드 7. Gin 작성 7.1. 데이터베이스 설정 7.2. 테이블, 스키마 정의 7.3.

Jan 2, 2022
Go-service-gin - Simple Web api application developed in Golang and Gin

Simple Web api application developed in Golang and Gin Initial Tutorial URL http

Jan 4, 2022
Go-gin-ddd-cqrs - Clean api rest with Go, Gin and GORM
Go-gin-ddd-cqrs - Clean api rest with Go, Gin and GORM

GOLANG API REST Clean api rest with Go, Gin and GORM. Clean Architecture with DD

Oct 21, 2022
Go-gin-mongo-api - A backend RESTful API built using golang, gin and mongoDB

go-gin-mongo-API This is a RESTful backend API which is developed using the gola

Jul 19, 2022
Gin-boilerplate - Gin boilerplate preconfigured with basic rest api features

Gin Boilerplate Build apis with gin faster with this template Features Validatio

Jun 24, 2022
Example golang using gin framework everything you need, i create this tutorial special for beginner.

Golang Gin Framework Fundamental Example golang using gin framework everything you need, i create this tutorial special for beginner. Feature Containe

Dec 16, 2022
A restful api's with Gin Framework with a structured project that defaults to PostgreSQL database
A restful api's with Gin Framework with a structured project that defaults to PostgreSQL database

Welcome to Golang Gin boilerplate v2 The fastest way to deploy a restful api's with Gin Framework with a structured project that defaults to PostgreSQ

Oct 15, 2021