Skip to content

Latest commit

 

History

History
70 lines (52 loc) · 2.33 KB

File metadata and controls

70 lines (52 loc) · 2.33 KB

🧯 Errors

Go Doc License Coverage Test

Errors is a library for handling errors gracefully in Go.

阅读中文版的 Read me

🙋‍ Features

  • Handling errors gracefully, yep, that's all...

Check HISTORY.md and FUTURE.md to know about more information.

package main

import (
	"fmt"
	"io"

	"github.com/FishGoddess/errors"
)

func main() {
	// Use wrap function to create an *Error error which has code and message.
	// You can get code and message of err anytime.
	err := errors.Wrap(1000, "need login")
	fmt.Println(err)
	fmt.Println(err.Code(), err.Message())

	// Try these ways to get code and message!
	// You will get default code or message if err doesn't have a code or message.
	code := errors.Code(err, 6699)
	message := errors.Message(err, "default message")
	fmt.Println(code, message)

	code = errors.Code(io.EOF, 6699)
	message = errors.Message(io.EOF, "default message")
	fmt.Println(code, message)

	// Also, we provide some useful information carrier for you.
	// For examples, you can carry an error, caller information or some args.
	// Remember the count of args should be even and their keys should be a string.
	err = errors.Wrap(9999, "io timeout").With(io.EOF).WithCaller().WithArgs("user_id", 123, "timeout", "200ms")
	fmt.Println(err)
	fmt.Println(errors.CodeMessage(err, 6666, "default message"))

	// What's more, we provide some shortcuts for you.
	// All these ways are returning *Error and you are free to use all methods on *Error.
	berr := errors.BadRequest("id is wrong")
	ferr := errors.Forbidden("user isn't allowed")
	nerr := errors.NotFound("book not found")
	fmt.Printf("%+v\n%+v\n%+v\n", berr, ferr, nerr)

	isBadRequest := errors.IsBadRequest(berr)
	isForbidden := errors.IsForbidden(ferr)
	isNotFound := errors.IsNotFound(nerr)
	fmt.Printf("isBadRequest: %+v\nisForbidden: %+v\nisNotFound: %+v\n", isBadRequest, isForbidden, isNotFound)
}

👥 Contributing

If you find that something is not working as expected, just fork and fix by yourself or open an issue :).