DEV Community

Cover image for Minimum Library to Handle Error for Go
maru44
maru44

Posted on • Edited on

Minimum Library to Handle Error for Go

Introduction

I made an error library named perr.

Perr gives error persona and enrich error.
You can handle error properly, safely and easily with perr.

Link:
https://github.com/maru44/perr

image ref:
https://pixabay.com/ja/?utm_source=link-attribution&utm_medium=referral&utm_campaign=image&utm_content=2661641

Purpose

Why I made this.

main purpose

  • I think errors must possess their persona.
    • For client(which means client side and user using your service)
    • For developer

For example, dial tcp 127.0.0.1:3306: connect: connection refused must not be shown for client. At the same time, Internal Server Error is not enough for developer.

sub purpose

  • Map() and Json() method make it easy to store and analyze error for you.
  • Is() and Level() method make it easy to handle error.
  • You can trace error with Traces() method.

Sample

wrapping error

You can wrap an error has existed already.
You can wrap an error as many times as you like.

package main

import (
    "fmt"
    "strconv"

    "github.com/maru44/perr"
)

func main() {
    _, err := strconv.Atoi("a")

    p := perr.Wrap(err, perr.BadRequest)
    p2 := perr.Wrap(p, perr.BadRequest)
    p3 := perr.Wrap(p2, perr.InternalServerError)

    fmt.Println("developer:", p3)
    fmt.Println("client:", p3.Output())

    fmt.Println("\n", p3.Traces())
}

/* output */
// developer: strconv.Atoi: parsing "a": invalid syntax
// client: Bad Request

// /tmp/sandbox2199832404/prog.go:13 ===> main
//  /tmp/sandbox2199832404/prog.go:14 ===> main
//      /tmp/sandbox2199832404/prog.go:15 ===> main
Enter fullscreen mode Exit fullscreen mode

new error

package main

import (
    "fmt"

    "github.com/maru44/perr"
)

func main() {
    p:= perr.New("Someone pour coffee", perr.IAmATeaPot)

    fmt.Println("developer: ", p)
    fmt.Println("client: ", p.Output())

    p2 := perr.New("", perr.IAmATeaPot)
    fmt.Println("\ndeveloper: ", p2)
    fmt.Println("client: ", p2.Output())
}

/* output */
// developer:  Someone pour coffee
// client:  I'm a teapot

// developer:  I'm a teapot
// client:  I'm a teapot
Enter fullscreen mode Exit fullscreen mode

Top comments (0)