package errors

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

Package errors provide an error type with code.

Index

Examples

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 any) 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

Code:play 

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.

Source Files

errors.go

Version
v0.60.0 (latest)
Published
Feb 1, 2025
Platform
linux/amd64
Imports
2 packages
Last checked
9 hours ago

Tools for package owners.