Giter Club home page Giter Club logo

ecode's Introduction

统一错误码

说明

根据bilibili的微服务框架kratos错误码修改而来,加入对信息的format功能

quick start

  1. 定义错误
    // 第一参数为自定义错误码
    // 第二个参数为http状态码
    // 第三个错误为错误信息
    InvalidParamsErr := NewCode(4000001, 400, "参数错误")
    // 打印方法
    fmt.Println(InvalidParamsErr.Code(), InvalidParamsErr.HttpCode(), InvalidParamsErr.Error())
    
    // 错误信息可以format的错误
    UserNotFound := NewCode(4040001, 404, "用户%s不存在")
    // 打印方法
    fmt.Println(UserNotFound.Code(), UserNotFound.HttpCode(), UserNotFound.SetArgs("123").Error())
    
    // 错误组,根据http状态码分类
    // 创建 http状态码为400的组
    group := NewGroup(400)
    // 创建错误,错误的http状态码都会是400
    BindErr := group.New(4000002, "参数解析错误")
    // 打印方法
    fmt.Println(BindErr.Code(), BindErr.HttpCode(), BindErr.Error())
    
  2. 使用
    // 推荐返回为error,更通用
    err := func() error {
    	return InvalidParamsErr
    }()
    // Cause方法根据err 反推回自定义code
    // 如果未找到自定义code,则返回服务器错误
    code := Cause(err)
    fmt.Println(code.Code(), code.HttpCode(), code.Error())
    
    // format的错误信息
    err = func() error {
    	return UserNotFound.SetArgs("123")
    }()
    code = Cause(err)
    fmt.Println(code.Code(), code.HttpCode(), code.Error())
    

说明

  • 默认code

ecode's People

Watchers

 avatar  avatar  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.