httperr

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Jun 11, 2021 License: GPL-3.0 Imports: 5 Imported by: 0

README

httperr Go Reference

Helper error for wrapping golang error with HTTP Status Code and stacktrace.

Usage

go get -u github.com/ClavinJune/httperr@latest

Example

package main

import (
	"database/sql"
	"errors"
	"fmt"
	"net/http"

	"github.com/ClavinJune/httperr"
)

func main() {
	// simple HTTP Error
	_ = httperr.From(http.StatusNotFound)
	base := httperr.New(sql.ErrNoRows, http.StatusNotFound, "user not found")
	wrapBase := httperr.Wrap(base, "wrap base with message")
	wrapAgain := httperr.Wrap(wrapBase, "once again, wrapped")

	fmt.Println(wrapAgain)
	/* stdout:
	   {
	     "cause": {
	       "cause": {
	         "error": "sql: no rows in result set",
	         "message": "user not found",
	         "caller": "main.go:13"
	       },
	       "message": "wrap base with message",
	       "caller": "main.go:14"
	     },
	     "message": "once again, wrapped",
	     "caller": "main.go:15"
	   }
	*/
	fmt.Println(errors.Is(wrapAgain, sql.ErrNoRows)) // stdout: true

	var ee *httperr.Error
	if errors.As(wrapAgain, &ee) {
		fmt.Println(ee.StatusCode()) // stdout: 404
	}
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrBaseNil = errors.New("httperr: base error is nil")
)

Functions

func From

func From(statusCode int) error

From creates new error from defined statusCode if statusCode doesn't have any status text statusCode changed to http.StatusInternalServerError

func New

func New(err error, statusCode int, message string) error

New wraps err with defined statusCode and message

func Wrap

func Wrap(err error, msg string) error

Wrap wraps err with custom message Wrap's result inherit statusCode from err if err equals *Error

Types

type Error

type Error struct {
	Err error
	// contains filtered or unexported fields
}

Error implements built in error with status code, caller, and message attribute it is recommended to create Error from the provided method instead of creating right from the struct to fill the caller.

func (Error) Error

func (e Error) Error() string

Error returns error message with caller

func (Error) StatusCode

func (e Error) StatusCode() int

StatusCode returns e.statusCode

func (Error) Unwrap

func (e Error) Unwrap() error

Unwrap enables errors.As and errors.Is

Jump to

Keyboard shortcuts

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