Skip to content
Myr

errors.go

This file

Path

errors.go

173 lines · 3.9 KiB · Go

Last changed by

fix: Correct typos, improve documentation clarity, and remove dead code (#4511)Mahan Adhikaribefore adoption8e07d37

History of this file

Take it

1// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2// Use of this source code is governed by a MIT style3// license that can be found in the LICENSE file.45package gin67import (8	"fmt"9	"reflect"10	"strings"1112	"github.com/gin-gonic/gin/codec/json"13)1415// ErrorType is an unsigned 64-bit error code as defined in the gin spec.16type ErrorType uint641718const (19	// ErrorTypeBind is used when Context.Bind() fails.20	ErrorTypeBind ErrorType = 1 << 6321	// ErrorTypeRender is used when Context.Render() fails.22	ErrorTypeRender ErrorType = 1 << 6223	// ErrorTypePrivate indicates a private error.24	ErrorTypePrivate ErrorType = 1 << 025	// ErrorTypePublic indicates a public error.26	ErrorTypePublic ErrorType = 1 << 127	// ErrorTypeAny indicates any other error.28	ErrorTypeAny ErrorType = 1<<64 - 129)3031// Error represents a error's specification.32type Error struct {33	Err  error34	Type ErrorType35	Meta any36}3738type errorMsgs []*Error3940var _ error = (*Error)(nil)4142// SetType sets the error's type.43func (msg *Error) SetType(flags ErrorType) *Error {44	msg.Type = flags45	return msg46}4748// SetMeta sets the error's meta data.49func (msg *Error) SetMeta(data any) *Error {50	msg.Meta = data51	return msg52}5354// JSON creates a properly formatted JSON55func (msg *Error) JSON() any {56	jsonData := H{}57	if msg.Meta != nil {58		value := reflect.ValueOf(msg.Meta)59		switch value.Kind() {60		case reflect.Struct:61			return msg.Meta62		case reflect.Map:63			for _, key := range value.MapKeys() {64				jsonData[key.String()] = value.MapIndex(key).Interface()65			}66		default:67			jsonData["meta"] = msg.Meta68		}69	}70	if _, ok := jsonData["error"]; !ok {71		jsonData["error"] = msg.Error()72	}73	return jsonData74}7576// MarshalJSON implements the json.Marshaller interface.77func (msg *Error) MarshalJSON() ([]byte, error) {78	return json.API.Marshal(msg.JSON())79}8081// Error implements the error interface.82func (msg Error) Error() string {83	return msg.Err.Error()84}8586// IsType judges one error.87func (msg *Error) IsType(flags ErrorType) bool {88	return (msg.Type & flags) > 089}9091// Unwrap returns the wrapped error, to allow interoperability with errors.Is(), errors.As() and errors.Unwrap()92func (msg Error) Unwrap() error {93	return msg.Err94}9596// ByType returns a readonly copy filtered the byte.97// ie ByType(gin.ErrorTypePublic) returns a slice of errors with type=ErrorTypePublic.98func (a errorMsgs) ByType(typ ErrorType) errorMsgs {99	if len(a) == 0 {100		return nil101	}102	if typ == ErrorTypeAny {103		return a104	}105	var result errorMsgs106	for _, msg := range a {107		if msg.IsType(typ) {108			result = append(result, msg)109		}110	}111	return result112}113114// Last returns the last error in the slice. It returns nil if the array is empty.115// Shortcut for errors[len(errors)-1].116func (a errorMsgs) Last() *Error {117	if length := len(a); length > 0 {118		return a[length-1]119	}120	return nil121}122123// Errors returns an array with all the error messages.124// Example:125//126//	c.Error(errors.New("first"))127//	c.Error(errors.New("second"))128//	c.Error(errors.New("third"))129//	c.Errors.Errors() // == []string{"first", "second", "third"}130func (a errorMsgs) Errors() []string {131	if len(a) == 0 {132		return nil133	}134	errorStrings := make([]string, len(a))135	for i, err := range a {136		errorStrings[i] = err.Error()137	}138	return errorStrings139}140141func (a errorMsgs) JSON() any {142	switch length := len(a); length {143	case 0:144		return nil145	case 1:146		return a.Last().JSON()147	default:148		jsonData := make([]any, length)149		for i, err := range a {150			jsonData[i] = err.JSON()151		}152		return jsonData153	}154}155156// MarshalJSON implements the json.Marshaller interface.157func (a errorMsgs) MarshalJSON() ([]byte, error) {158	return json.API.Marshal(a.JSON())159}160161func (a errorMsgs) String() string {162	if len(a) == 0 {163		return ""164	}165	var buffer strings.Builder166	for i, msg := range a {167		fmt.Fprintf(&buffer, "Error #%02d: %s\n", i+1, msg.Err)168		if msg.Meta != nil {169			fmt.Fprintf(&buffer, "     Meta: %v\n", msg.Meta)170		}171	}172	return buffer.String()173}