Code Monkey home page Code Monkey logo

gin-error-handler's Introduction

gin-error-handler

Automatically returns JSON when you don't want to bother with every err!=nil, using Gin framework.

Usage

Copy the eh.go and preset.go file to wherever you want.

Define your Data Transfer Object with "eh" tags.

There are 3 meaningful tags, others stand for default values:

  1. eh:"err" - the field with err tag will be returned as a string, its value equals to err.Error()
  2. eh:"" - the field with empty tag will remain the default value of the type, you can also omit the tag
  3. eh:"pre:" - the field will be set the same as the variable in Preset struct with the same name, e.g. field with pre:CodeOK will be set with Preset.CodeOK (200, int64). Be aware of the spelling: p,r,e,colon. The type of the original field and the according " Preset variable" must be the same, otherwise will cause a panic.

Example

package main

import (
	"errors"
	"fmt"
	eh "gin-error-handler"
	"github.com/gin-gonic/gin"
	"net/http"
	"net/http/httptest"
)

type User struct {
	Name string `json:"name,omitempty"`
}

type UserLoginResp struct {
	Seq  int64  `json:"seq" eh:"-1"`                     // will be -1
	Code int64  `json:"code" eh:"pre:CodeUncaughtError"` // will be filled with Preset.CodeUncaughtError (551)
	Msg  string `json:"msg" eh:"err"`                    // will eventually be err.Error()
	User *User  `json:"user,omitempty" eh:""`            // will omit this field
}

func handler(c *gin.Context) {
	// create a new handler with *gin.Context and your JSON interface
	errHandler := eh.JSONHandler{
		C: c,
		V: UserLoginResp{},
	}
	err := errors.New("something went wrong")              // some error occurred
	errHandler.Handle(err, http.StatusInternalServerError) // handle the error
	//errHandler.Handle(err) // will use http.StatusOK if you don't specify the code                // handle the error
}

func main() {
	req, _ := http.NewRequest(http.MethodGet, "/err", nil) // make a mock request
	rec := httptest.NewRecorder()                          // record the mock request
	// use Gin to handle the request
	r := gin.Default()
	r.GET("/err", handler)
	r.ServeHTTP(rec, req)
	fmt.Println(rec.Body.String())
}

Output

{"seq":-1,"code":551,"msg":"something went wrong"}

gin-error-handler's People

Contributors

zenpk avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.