errors

package
v12.2.11 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2024 License: BSD-3-Clause Imports: 15 Imported by: 6

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// Is is an alias of the standard errors.Is function.
	Is = errors.Is
	// As is an alias of the standard errors.As function.
	As = errors.As
	// New is an alias of the standard errors.New function.
	New = errors.New
	// Unwrap is an alias of the standard errors.Unwrap function.
	Unwrap = errors.Unwrap
	// Join is an alias of the standard errors.Join function.
	Join = errors.Join
)
View Source
var (
	// ErrUnexpected is the HTTP error which sent to the client
	// when server fails to send an error, it's a fallback error.
	// The server fails to send an error on two cases:
	// 1. when the provided error code name is not registered (the error value is the ErrUnexpectedErrorCode)
	// 2. when the error contains data but cannot be encoded to json (the value of the error is the result error of json.Marshal).
	ErrUnexpected = Register("UNEXPECTED_ERROR", http.StatusInternalServerError)
	// ErrUnexpectedErrorCode is the error which logged
	// when the given error code name is not registered.
	ErrUnexpectedErrorCode = New("unexpected error code name")
)
View Source
var DefaultContextErrorHandler context.ErrorHandler = new(jsonErrorHandler)

DefaultContextErrorHandler returns a context error handler which calls the HandleError on any incoming error when a rich rest response failed to be written to the client. Register it on Application.SetContextErrorHandler method.

View Source
var DefaultPathParameterTypeErrorHandler handler.ParamErrorHandler = func(ctx *context.Context, paramIndex int, err error) {
	param := ctx.Params().GetEntryAt(paramIndex)
	InvalidArgument.DataWithDetails(ctx, "invalid path parameter", err.Error(), param)
}

DefaultPathParameterTypeErrorHandler registers an error handler for macro path type parameter. Register it with Application.Macros().SetErrorHandler(DefaultPathParameterTypeErrorHandler).

Deprecated: Use Register instead.

View Source
var SkipCanceled = true

SkipCanceled is a package-level setting which by default skips the logging of a canceled response or operation. See the "Context.IsCanceled()" method and "iris.IsCanceled()" function that decide if the error is caused by a canceled operation.

Change of this setting MUST be done on initialization of the program.

Functions

func Create added in v12.2.9

func Create[T, R any, F ResponseFunc[T, R]](ctx *context.Context, fn F, fnInput ...T) bool

Create handles a create operation and sends a JSON response with the created resource to the client. It returns a boolean value indicating whether the handle was successful or not. If the error is not nil, it calls HandleError to send an appropriate error response to the client. It sets the status code to 201 (Created) and sends any response as a JSON payload note that if the response is a string, then it sends an {"id": resp} JSON payload).

Useful for Insert operations.

func CreateHandler added in v12.2.9

func CreateHandler[T, R any, F ResponseFunc[T, R], I HandlerInputFunc[T]](fn F, fnInput ...I) context.Handler

CreateHandler handles a create operation and sends a JSON response with the created resource to the client with status code of 201.

See Create package-level function for more.

func GetRequestInputs added in v12.2.9

func GetRequestInputs[T any, I HandlerInputFunc[T]](ctx *context.Context, fnInputFunc []I) ([]T, bool)

GetRequestInputs returns a slice of generic type T from a slice of HandlerInputFunc[T]. It is exported so end-developers can use it to get the inputs from custom HandlerInputFunc[T] functions.

func Handle added in v12.2.9

func Handle(ctx *context.Context, resp interface{}, err error) bool

Handle handles a generic response and error from a service call and sends a JSON response to the client. It returns a boolean value indicating whether the handle was successful or not. If the error is not nil, it calls HandleError to send an appropriate error response to the client.

func HandleAPIError

func HandleAPIError(ctx *context.Context, err error)

HandleAPIError handles remote server errors. Optionally, use it when you write your server's HTTP clients using the the /x/client package. When the HTTP Client sends data to a remote server but that remote server failed to accept the request as expected, then the error will be proxied to this server's end-client.

When the given "err" is not a type of client.APIError then the error will be sent using the "Internal.LogErr" method which sends HTTP internal server error to the end-client and prints the "err" using the "LogError" package-level function.

func HandleCreate added in v12.2.9

func HandleCreate(ctx *context.Context, respOrID any, err error) bool

HandleCreate handles a create operation and sends a JSON response with the created resource to the client. It returns a boolean value indicating whether the handle was successful or not.

If the "respOrID" response is not nil, it sets the status code to 201 (Created) and sends the response as a JSON payload, however if the given "respOrID" is a string or an int, it sends the response as a JSON payload of {"id": resp}. If the "err" error is not nil, it calls HandleError to send an appropriate error response to the client. It sets the status code to 201 (Created) and sends any response as a JSON payload,

func HandleDelete added in v12.2.9

func HandleDelete(ctx *context.Context, deleted bool, err error) bool

HandleDelete handles a delete operation and sends a status code to the client. If the error is not nil, it calls HandleError to send an appropriate error response to the client. If the deleted value is true, it sets the status code to 204 (No Content). If the deleted value is false, it sets the status code to 304 (Not Modified).

func HandleDeleteNoContent added in v12.2.9

func HandleDeleteNoContent(ctx *context.Context, err error) bool

HandleDelete handles a delete operation and sends a status code to the client. If the error is not nil, it calls HandleError to send an appropriate error response to the client. It sets the status code to 204 (No Content).

func HandleError added in v12.2.9

func HandleError(ctx *context.Context, err error) bool

HandleError handles an error by sending it to the client based on the registered error code names and their error functions. Returns true if the error was handled, otherwise false. If the given "err" is nil then it returns false. If the given "err" is a type of validation error then it sends it to the client using the "Validation" method. If the given "err" is a type of client.APIError then it sends it to the client using the "HandleAPIError" function.

See ErrorCodeName.MapErrorFunc and MapErrors methods too.

func HandleUpdate added in v12.2.9

func HandleUpdate(ctx *context.Context, updated bool, err error) bool

HandleUpdate handles an update operation and sends a status code to the client. It returns a boolean value indicating whether the handle was successful or not. If the error is not nil, it calls HandleError to send an appropriate error response to the client. If the updated value is true, it sets the status code to 204 (No Content). If the updated value is false, it sets the status code to 304 (Not Modified).

func Handler added in v12.2.9

func Handler[T, R any, F ResponseFunc[T, R], I HandlerInputFunc[T]](fn F, fnInput ...I) context.Handler

Handler handles a generic response and error from a service call and sends a JSON response to the client with status code of 200.

See OK package-level function for more.

func Intercept added in v12.2.11

func Intercept[T, R any](responseHandlers ...ContextResponseFunc[T, R]) context.Handler

Intercept adds a context response handler function to the context. It returns a middleware which can be used to intercept the response before sending it to the client.

Example Code:

app.Post("/", errors.Intercept(func(ctx iris.Context, req *CreateRequest, resp *CreateResponse) error{ ... }), errors.CreateHandler(service.Create))

func List added in v12.2.9

func List[T, R any, C constraints.Integer | constraints.Float, F ListResponseFunc[T, R, C]](ctx *context.Context, fn F, fnInput ...T) bool

List handles a generic response and error from a service paginated call and sends a JSON response to the client. It returns a boolean value indicating whether the handle was successful or not. If the error is not nil, it calls HandleError to send an appropriate error response to the client. It reads the pagination.ListOptions from the URL Query and any filter options of generic T from the request body. It sets the status code to 200 (OK) and sends a *pagination.List[R] response as a JSON payload.

func ListHandler added in v12.2.9

func ListHandler[T, R any, C constraints.Integer | constraints.Float, F ListResponseFunc[T, R, C], I HandlerInputFunc[T]](fn F, fnInput ...I) context.Handler

ListHandler handles a generic response and error from a service paginated call and sends a JSON response to the client.

See List package-level function for more.

func NoContent added in v12.2.9

func NoContent[T any, F ResponseOnlyErrorFunc[T]](ctx *context.Context, fn F, fnInput ...T) bool

NoContent handles a generic response and error from a service call and sends a JSON response to the client. It returns a boolean value indicating whether the handle was successful or not. If the error is not nil, it calls HandleError to send an appropriate error response to the client. It sets the status code to 204 (No Content).

Useful for Update and Deletion operations.

func NoContentHandler added in v12.2.9

func NoContentHandler[T any, F ResponseOnlyErrorFunc[T], I HandlerInputFunc[T]](fn F, fnInput ...I) context.Handler

NoContentHandler handles a generic response and error from a service call and sends a JSON response to the client with status code of 204.

See NoContent package-level function for more.

func NoContentOrNotModified added in v12.2.9

func NoContentOrNotModified[T any, F ResponseFunc[T, bool]](ctx *context.Context, fn F, fnInput ...T) bool

NoContent handles a generic response and error from a service call and sends a JSON response to the client. It returns a boolean value indicating whether the handle was successful or not. If the error is not nil, it calls HandleError to send an appropriate error response to the client. If the response is true, it sets the status code to 204 (No Content). If the response is false, it sets the status code to 304 (Not Modified).

Useful for Update and Deletion operations.

func NoContentOrNotModifiedHandler added in v12.2.9

func NoContentOrNotModifiedHandler[T any, F ResponseFunc[T, bool], I HandlerInputFunc[T]](fn F, fnInput ...I) context.Handler

NoContentOrNotModifiedHandler handles a generic response and error from a service call and sends a JSON response to the client with status code of 204 or 304.

See NoContentOrNotModified package-level function for more.

func OK added in v12.2.9

func OK[T, R any, F ResponseFunc[T, R]](ctx *context.Context, fn F, fnInput ...T) bool

OK handles a generic response and error from a service call and sends a JSON response to the client. It returns a boolean value indicating whether the handle was successful or not. If the error is not nil, it calls HandleError to send an appropriate error response to the client. It sets the status code to 200 (OK) and sends any response as a JSON payload.

Useful for Get/List/Fetch operations.

func PathParam added in v12.2.9

func PathParam[T any, I HandlerInputFunc[T]](paramName string) I

PathParam returns a HandlerInputFunc which reads a path parameter from the context and returns it as a generic type T. It is used for XHandler functions.

func Query added in v12.2.9

func Query[T any, I HandlerInputFunc[T]]() I

Query returns a HandlerInputFunc which reads a URL query from the context and returns it as a generic type T. It is used for XHandler functions.

func ReadPaginationOptions added in v12.2.9

func ReadPaginationOptions[T any](ctx *context.Context) (pagination.ListOptions, T, bool)

ReadPaginationOptions reads the ListOptions from the URL Query and any filter options of generic T from the request body.

func ReadPayload added in v12.2.9

func ReadPayload[T any](ctx *context.Context) (T, bool)

ReadPayload reads a JSON payload from the context and returns it as a generic type T. It also returns a boolean value indicating whether the read was successful or not. If the read fails, it sends an appropriate error response to the client.

func ReadQuery added in v12.2.9

func ReadQuery[T any](ctx *context.Context) (T, bool)

ReadQuery reads URL query values from the context and returns it as a generic type T. It also returns a boolean value indicating whether the read was successful or not. If the read fails, it sends an appropriate error response to the client.

func RecoveryHandler added in v12.2.9

func RecoveryHandler(ctx *context.Context)

RecoveryHandler is a middleware which recovers from panics and sends an appropriate error response to the logger and the client.

func RegisterErrorCode

func RegisterErrorCode(canonicalName ErrorCodeName, httpStatusCode int)

RegisterErrorCode registers a custom HTTP Error.

This method MUST be called on initialization, before HTTP server starts as the internal map is not protected by mutex.

func RegisterErrorCodeMap

func RegisterErrorCodeMap(errorMap map[ErrorCodeName]int)

RegisterErrorCodeMap registers one or more custom HTTP Errors.

This method MUST be called on initialization, before HTTP server starts as the internal map is not protected by mutex.

func Validation added in v12.2.9

func Validation[T any](validators ...ContextRequestFunc[T]) context.Handler

Validation adds a context validator function to the context. It returns a middleware which can be used to validate the context before calling a service function. It panics if the given validators are empty or nil.

Example:

r.Post("/", Validation(validateCreateRequest), createHandler(service))

func validateCreateRequest(ctx iris.Context, r *CreateRequest) error {
	return validation.Join(
		validation.String("fullname", r.Fullname).NotEmpty().Fullname().Length(3, 50),
		validation.Number("age", r.Age).InRange(18, 130),
		validation.Slice("hobbies", r.Hobbies).Length(1, 10),
	)
}

func Value added in v12.2.9

func Value[T any, I HandlerInputFunc[T]](value T) I

Value returns a HandlerInputFunc which returns a generic type T. It is used for XHandler functions.

Types

type ContextRequestFunc added in v12.2.11

type ContextRequestFunc[T any] func(*context.Context, T) error

ContextRequestFunc is a function which takes a context and a generic type T and returns an error. It is used to validate the context before calling a service function.

See Validation package-level function.

type ContextResponseFunc added in v12.2.11

type ContextResponseFunc[T, R any] func(*context.Context, T, *R) error

ContextResponseFunc is a function which takes a context, a generic type T and a generic type R and returns an error.

type Error

type Error struct {
	ErrorCode  ErrorCode       `json:"http_error_code" yaml:"HTTPErrorCode"`
	Message    string          `json:"message,omitempty" yaml:"Message"`
	Details    string          `json:"details,omitempty" yaml:"Details"`
	Validation interface{}     `json:"validation,omitempty" yaml:"Validation,omitempty"`
	Data       json.RawMessage `json:"data,omitempty" yaml:"Data,omitempty"` // any other custom json data.
}

Error represents the JSON form of "http wire errors".

Examples can be found at:

https://github.com/kataras/iris/tree/main/_examples/routing/http-wire-errors.

func (*Error) Error

func (err *Error) Error() string

Error method completes the error interface. It just returns the canonical name, status code, message and details.

type ErrorCode

type ErrorCode struct {
	CanonicalName ErrorCodeName `json:"canonical_name" yaml:"CanonicalName"`
	Status        int           `json:"status" yaml:"Status"`
}

ErrorCode represents the JSON form ErrorCode of the Error.

type ErrorCodeName

type ErrorCodeName string

ErrorCodeName is a custom string type represents canonical error names.

It contains functionality for safe and easy error populating. See its "Message", "Details", "Data" and "Log" methods.

var (
	Cancelled          ErrorCodeName = Register("CANCELLED", context.StatusTokenRequired)
	Unknown            ErrorCodeName = Register("UNKNOWN", http.StatusInternalServerError)
	InvalidArgument    ErrorCodeName = Register("INVALID_ARGUMENT", http.StatusBadRequest)
	DeadlineExceeded   ErrorCodeName = Register("DEADLINE_EXCEEDED", http.StatusGatewayTimeout)
	NotFound           ErrorCodeName = Register("NOT_FOUND", http.StatusNotFound)
	AlreadyExists      ErrorCodeName = Register("ALREADY_EXISTS", http.StatusConflict)
	PermissionDenied   ErrorCodeName = Register("PERMISSION_DENIED", http.StatusForbidden)
	Unauthenticated    ErrorCodeName = Register("UNAUTHENTICATED", http.StatusUnauthorized)
	ResourceExhausted  ErrorCodeName = Register("RESOURCE_EXHAUSTED", http.StatusTooManyRequests)
	FailedPrecondition ErrorCodeName = Register("FAILED_PRECONDITION", http.StatusBadRequest)
	Aborted            ErrorCodeName = Register("ABORTED", http.StatusConflict)
	OutOfRange         ErrorCodeName = Register("OUT_OF_RANGE", http.StatusBadRequest)
	Unimplemented      ErrorCodeName = Register("UNIMPLEMENTED", http.StatusNotImplemented)
	Internal           ErrorCodeName = Register("INTERNAL", http.StatusInternalServerError)
	Unavailable        ErrorCodeName = Register("UNAVAILABLE", http.StatusServiceUnavailable)
	DataLoss           ErrorCodeName = Register("DATA_LOSS", http.StatusInternalServerError)
)

List of default error codes a server should follow and send back to the client.

func Register added in v12.2.9

func Register(httpErrorCanonicalName string, httpStatusCode int) ErrorCodeName

Register registers a custom HTTP Error and returns its canonical name for future use. The method "New" is reserved and was kept as it is for compatibility with the standard errors package, therefore the "Register" name was chosen instead. The key stroke "e" is near and accessible while typing the "errors" word so developers may find it easy to use.

See "RegisterErrorCode" and "RegisterErrorCodeMap" for alternatives.

Example:

	var (
   		NotFound = errors.Register("NOT_FOUND", http.StatusNotFound)
	)
	...
	NotFound.Details(ctx, "resource not found", "user with id: %q was not found", userID)

This method MUST be called on initialization, before HTTP server starts as the internal map is not protected by mutex.

func (ErrorCodeName) Data

func (e ErrorCodeName) Data(ctx *context.Context, msg string, data interface{})

Data sends an error with a message and json data to the client.

func (ErrorCodeName) DataWithDetails

func (e ErrorCodeName) DataWithDetails(ctx *context.Context, msg, details string, data interface{})

DataWithDetails sends an error with a message, details and json data to the client.

func (ErrorCodeName) Details

func (e ErrorCodeName) Details(ctx *context.Context, msg, details string, detailsArgs ...interface{})

Details sends an error with a message and details to the client.

func (ErrorCodeName) Err

func (e ErrorCodeName) Err(ctx *context.Context, err error)

Err sends the error's text as a message to the client. In exception, if the given "err" is a type of validation error then the Validation method is called instead.

func (ErrorCodeName) Error added in v12.2.9

func (e ErrorCodeName) Error() string

Error returns an empty string, it is only declared as a method of ErrorCodeName type in order to be a compatible error to be joined within other errors:

err = fmt.Errorf("%w%w", errors.InvalidArgument, err) OR
err = errors.InvalidArgument.Wrap(err)

func (ErrorCodeName) Log

func (e ErrorCodeName) Log(ctx *context.Context, format string, args ...interface{})

Log sends an error of "format" and optional "args" to the client and prints that error using the "LogError" package-level function, which can be customized.

See "LogErr" too.

func (ErrorCodeName) LogErr

func (e ErrorCodeName) LogErr(ctx *context.Context, err error)

LogErr sends the given "err" as message to the client and prints that error to using the "LogError" package-level function, which can be customized.

func (ErrorCodeName) MapErrorFunc added in v12.2.9

func (e ErrorCodeName) MapErrorFunc(fn func(error) error)

MapErrorFunc registers a function which will validate the incoming error and return the same error or overriden in order to be sent to the client, wrapped by this ErrorCodeName "e".

This method MUST be called on initialization, before HTTP server starts as the internal map is not protected by mutex.

Example Code:

errors.InvalidArgument.MapErrorFunc(func(err error) error {
	stripeErr, ok := err.(*stripe.Error)
	if !ok {
		return nil
	}

	return &errors.Error{
		Message: stripeErr.Msg,
		Details: stripeErr.DocURL,
	}
})

func (ErrorCodeName) MapErrors added in v12.2.9

func (e ErrorCodeName) MapErrors(targets ...error)

MapError registers one or more errors which will be sent to the client wrapped by this "e" ErrorCodeName when the incoming error matches to at least one of the given "targets" one.

This method MUST be called on initialization, before HTTP server starts as the internal map is not protected by mutex.

func (ErrorCodeName) Message

func (e ErrorCodeName) Message(ctx *context.Context, format string, args ...interface{})

Message sends an error with a simple message to the client.

func (ErrorCodeName) Validation

func (e ErrorCodeName) Validation(ctx *context.Context, validationErrors ...ValidationError)

Validation sends an error which renders the invalid fields to the client.

func (ErrorCodeName) Wrap added in v12.2.9

func (e ErrorCodeName) Wrap(err error) error

Wrap wraps the given error with this ErrorCodeName. It calls the standard errors.Join package-level function. See HandleError function for more.

type HandlerInputFunc added in v12.2.9

type HandlerInputFunc[T any] interface {
	func(ctx *context.Context) T
}

HandlerInputFunc is a function which takes a context and returns a generic type T. It is used to call a service function with a generic type T. It is used for functions which do not bind a request payload. It is used for XHandler functions. Developers can design their own HandlerInputFunc functions and use them with the XHandler functions. To make a value required, stop the context execution through the context.StopExecution function and fire an error or just use one of the InvalidArgument.X methods.

See PathParam, Query and Value package-level helpers too.

type IDPayload added in v12.2.9

type IDPayload[T string | int] struct {
	ID T `json:"id"`
}

IDPayload is a simple struct which describes a json id value.

type ListResponseFunc added in v12.2.9

type ListResponseFunc[T, R any, C constraints.Integer | constraints.Float] interface {
	func(stdContext.Context, pagination.ListOptions, T) ([]R, C, error)
}

ListResponseFunc is a function which takes a context, a pagination.ListOptions and a generic type T and returns a slice []R, total count of the items and an error.

It's used on the List function.

type LogErrorFunc

type LogErrorFunc = func(ctx *context.Context, err error)

LogErrorFunc is an alias of a function type which accepts the Iris request context and an error and it's fired whenever an error should be logged.

See "OnErrorLog" variable to change the way an error is logged, by default the error is logged using the Application's Logger's Error method.

var LogError LogErrorFunc = func(ctx *context.Context, err error) {
	if ctx == nil {
		slog.Error(err.Error())
		return
	}

	ctx.Application().Logger().Error(err)
}

LogError can be modified to customize the way an error is logged to the server (most common: internal server errors, database errors et.c.). Can be used to customize the error logging, e.g. using Sentry (cloud-based error console).

type RequestHandler added in v12.2.11

type RequestHandler interface {
	HandleRequest(*context.Context) error
}

RequestHandler is an interface which can be implemented by a request payload struct in order to validate the context before calling a service function.

type ResponseFunc added in v12.2.9

type ResponseFunc[T, R any] interface {
	func(stdContext.Context, T) (R, error)
}

ResponseFunc is a function which takes a context and a generic type T and returns a generic type R and an error. It is used to bind a request payload to a generic type T and call a service function with it.

type ResponseHandler added in v12.2.11

type ResponseHandler[R any] interface {
	HandleResponse(ctx *context.Context, response *R) error
}

ResponseHandler is an interface which can be implemented by a request payload struct in order to handle a response before sending it to the client.

type ResponseOnlyErrorFunc added in v12.2.9

type ResponseOnlyErrorFunc[T any] interface {
	func(stdContext.Context, T) error
}

ResponseOnlyErrorFunc is a function which takes a context and a generic type T and returns an error. It is used to bind a request payload to a generic type T and call a service function with it. It is used for functions which do not return a response.

type ValidationError

type ValidationError interface {
	error

	GetField() string
	GetValue() interface{}
	GetReason() string
}

ValidationError is an interface which IF it custom error types completes, then it can by mapped to a validation error.

A validation error(s) can be given by ErrorCodeName's Validation or Err methods.

type ValidationErrors

type ValidationErrors []ValidationError

func (ValidationErrors) Error

func (errs ValidationErrors) Error() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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