serr

package
v1.34.4 Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2023 License: Apache-2.0 Imports: 4 Imported by: 0

Documentation

Overview

Package serr This package contains all the logic and helper methods for creating and serializing API Errors This is in a separate package than server so that as a developer you get better intellisense when creating errors Heavily inspired from Nike Backstopper

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	// Code The business/project error code this instance represents (not to be confused with the HTTP status code which can be retrieved via HttpStatusCode).
	// This should never change for a given error so clients can rely on it and write code against it.
	Code int
	// Message the message that will be displayed the Client
	Message string
	// Metadata that about the error that will be returned to the client
	Metadata map[string]any
	// HttpStatusCode defaults to http.StatusInternalServerError if not overridden
	HttpStatusCode int
}

APIError is an error that gets embedded in ResponseContract when an error response is returned to the client

type Error

type Error interface {
	// Errors The collection of APIError associated with this instance.
	Errors() []APIError
	// ExtraDetailsForLogging Any extra details you want logged when this error is handled. Will never be null, but might be empty. NOTE: This will always be a mutable list so it can be modified at any time.
	ExtraDetailsForLogging() []KVPair
	// ExtraResponseHeaders Any extra headers you want sent to the origin when this error is handled.
	ExtraResponseHeaders() []KVPair
	// StackTraceLoggingBehavior Allows users to override the default behavior (logging stack traces for 5xx errors but not 4xx errors) and instead force stack trace on/off if they want to override the default 4xx vs. 5xx decision behavior.
	StackTraceLoggingBehavior() StackTraceLoggingBehavior
	// Message The error msg for logging, this will NOT be part of the server response
	Message() string
	// Cause The cause of the API error
	Cause() error
	// Stacktrace The stacktrace of the error
	Stacktrace() string
	// Origin the origination of the API error
	Origin() string
	// ToErrorResponseContract converts the Error into a ResponseContract
	ToErrorResponseContract(errorId string) ResponseContract
}

Error You'll want to create an instance using one of the New* functions in this package such as NewSimpleError, NewErrorResponseFromApiError, etc. e.g.

// A simple use case
serr.NewSimpleError("super useful message", someErrThatIsTheCauseThatWillBeLogged)

// A simple use case, where there isn't a cause
serr.NewSimpleError("super useful message", nil)

// A simple use case, where you want to override the default status code of 500
serr.NewSimpleErrorWithStatusCode("could not find the thing", http.StatusNotFound, nil)

// The kitchen sink
serr.NewErrorResponseFromApiError(serr.APIError{
	Message: "Server can not produce requested content type",
	Metadata: map[string]any{
		"requested": accept,
		"available": strings.Join(availableMimeTypes, ", "),
	},
	HttpStatusCode: http.StatusBadRequest,
},
	serr.WithErrorMessage("Some extra message for the logs, that replaces the default, can't handle request message"),
	serr.WithCause(err),
	serr.WithExtraDetailsForLogging(
		serr.KVPair{
			Key:   "requested-type",
			Value: accept,
		},
		serr.KVPair{
			Key:   "available-types",
			Value: strings.Join(availableMimeTypes, ", "),
		},
	))
	serr.WithExtraResponseHeaders(serr.KVPair{
		Key:   "X-Armory-Custom-header",
		Value: "custom header value",
	})
	serr.WithStackTraceLoggingBehavior(serr.ForceStackTrace) // tweak the stacktrace behavior
)

The generator functions accept many Option's that directly affect the response and what is logged, so take a close look at the available options.

func NewErrorResponseFromApiError

func NewErrorResponseFromApiError(error APIError, opts ...Option) Error

NewErrorResponseFromApiError Given a Single APIError and the given Option's returns an instance of Error

func NewErrorResponseFromApiErrors

func NewErrorResponseFromApiErrors(errors []APIError, opts ...Option) Error

NewErrorResponseFromApiErrors Given multiple APIError's and the given Option's returns an instance of Error

func NewSimpleError

func NewSimpleError(msgForResponse string, cause error) Error

NewSimpleError is a helper function that will create a serr.Error that satisfies most use cases.

Defaults to http.StatusInternalServerError (500) status code.

Use serr.NewSimpleErrorWithStatusCode to override the status code.

func NewSimpleErrorWithStatusCode

func NewSimpleErrorWithStatusCode(msgForResponse string, statusCodeForResponse int, cause error) Error

NewSimpleErrorWithStatusCode is a helper function that will create a serr.Error that satisfies most use cases

func NewWrappedErrorWithStatusCode added in v1.16.0

func NewWrappedErrorWithStatusCode(err error, statusCodeForResponse int) Error

NewWrappedErrorWithStatusCode is a helper function that creates a serr.Error from an error. It is appropriate to use when the provided err is intended for end-user consumption (e.g., a custom error message).

type KVPair

type KVPair struct {
	Key   string
	Value string
}

type Option

type Option func(aE *apiErrorResponse)

func WithCause

func WithCause(err error) Option

WithCause The given error will be stored and used in logging and ultimately become Error.Cause.

func WithErrorMessage

func WithErrorMessage(message string) Option

WithErrorMessage The error message for logging, this will NOT be part of the server response. Could be used as context for what went wrong if the API errors aren't self-explanatory. Will ultimately become Error.Message.

func WithExtraDetailsForLogging

func WithExtraDetailsForLogging(extraDetailsForLogging ...KVPair) Option

WithExtraDetailsForLogging Adds the given logging details to what will ultimately become Error.ExtraDetailsForLogging.

func WithExtraResponseHeaders

func WithExtraResponseHeaders(extraResponseHeaders ...KVPair) Option

WithExtraResponseHeaders Adds the given response headers to what will ultimately become Error.ExtraResponseHeaders.

func WithFrameSkips added in v1.24.4

func WithFrameSkips(framesToSkip int) Option

WithFrameSkips Overrides the number of frames to skip when generating the stack trace.

func WithStackTraceLoggingBehavior

func WithStackTraceLoggingBehavior(behavior StackTraceLoggingBehavior) Option

WithStackTraceLoggingBehavior Sets the given StackTraceLoggingBehavior for what will ultimately become Error.StackTraceLoggingBehavior.

type ResponseContract

type ResponseContract struct {
	ErrorId string                     `json:"error_id"`
	Errors  []ResponseContractErrorDTO `json:"errors"`
}

ResponseContract the strongly typed error contract that will be returned to the client if a request is not successful

type ResponseContractErrorDTO

type ResponseContractErrorDTO struct {
	Message  string         `json:"message"`
	Metadata map[string]any `json:"metadata,omitempty"`
	Code     string         `json:"code"`
}

type StackTraceLoggingBehavior

type StackTraceLoggingBehavior int
const (
	DeferToDefaultBehavior StackTraceLoggingBehavior = iota
	ForceStackTrace
	ForceNoStackTrace
)

Jump to

Keyboard shortcuts

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