errors

package
v0.54.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 4, 2024 License: BSD-3-Clause Imports: 2 Imported by: 2

Documentation

Overview

Package errors provide an error type with code.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type E

type E struct {
	Message string `json:"message,omitempty"`
	Name    string `json:"name,omitempty"`
	Code    int    `json:"code,omitempty"`
	// contains filtered or unexported fields
}

E define custom error that wrap underlying error with custom code, message, and name.

The Code field is required, used to communicate the HTTP response code. The Message field is optional, it's used to communicate the actual error message from server, to be readable by human. The Name field is optional, intended to be consumed by program, for example, to provide a key as translation of Message into user's locale defined language.

func Internal

func Internal(err error) *E

Internal define an error caused by server.

func InvalidInput

func InvalidInput(field string) *E

InvalidInput generate an error for invalid input.

func (*E) As

func (e *E) As(target interface{}) bool

As set the target to e only if only target is **E.

func (*E) Error

func (e *E) Error() string

Error implement the error interface.

func (*E) Is

func (e *E) Is(target error) bool

Is return true if the target error is instance of *E and the value of field Code and Name match with values in e.

Example
package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"log"

	liberrors "git.sr.ht/~shulhan/pakakeh.go/lib/errors"
)

func main() {
	var (
		errFileNotFound = &liberrors.E{
			Code:    400,
			Name:    `ERR_NOT_FOUND`,
			Message: `file not found`,
		}
		errResNotFound = &liberrors.E{
			Code:    404,
			Name:    `ERR_NOT_FOUND`,
			Message: `resource not found`,
		}

		rawJSON = `{"code":400,"name":"ERR_NOT_FOUND","message":"file not found"}`

		e   *liberrors.E
		err error
	)

	err = json.Unmarshal([]byte(rawJSON), &e)
	if err != nil {
		log.Fatal(err)
	}

	var gotErr error = e

	fmt.Println(errors.Is(gotErr, errFileNotFound))
	fmt.Println(errors.Is(gotErr, errResNotFound))

}
Output:

true
false

func (*E) Unwrap

func (e *E) Unwrap() error

Unwrap return the internal error.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL