Documentation ¶
Index ¶
- Variables
- func GetCaller() string
- func HandleCrash(additionalHandlers ...func(interface{}))
- func HandleCrashWithContext(ctx context.Context, additionalHandlers ...func(context.Context, interface{}))
- func HandleError(err error)
- func HandleErrorWithContext(ctx context.Context, err error, msg string, keysAndValues ...interface{})
- func Must(err error)
- func RecoverFromPanic(err *error)
- type ErrorHandler
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrorHandlers = []ErrorHandler{ logError, func(_ context.Context, _ error, _ string, _ ...interface{}) { (&rudimentaryErrorBackoff{ lastErrorTime: time.Now(), minPeriod: time.Millisecond, }).OnError() }, }
ErrorHandlers is a list of functions which will be invoked when a nonreturnable error occurs. TODO(lavalamp): for testability, this and the below HandleError function should be packaged up into a testable and reusable object.
var PanicHandlers = []func(context.Context, interface{}){logPanic}
PanicHandlers is a list of functions which will be invoked when a panic happens.
var ( // ReallyCrash controls the behavior of HandleCrash and defaults to // true. It's exposed so components can optionally set to false // to restore prior behavior. This flag is mostly used for tests to validate // crash conditions. ReallyCrash = true )
Functions ¶
func GetCaller ¶
func GetCaller() string
GetCaller returns the caller of the function that calls it.
func HandleCrash ¶
func HandleCrash(additionalHandlers ...func(interface{}))
HandleCrash simply catches a crash and logs an error. Meant to be called via defer. Additional context-specific handlers can be provided, and will be called in case of panic. HandleCrash actually crashes, after calling the handlers and logging the panic message.
E.g., you can provide one or more additional handlers for something like shutting down go routines gracefully.
TODO(pohly): logcheck:context // HandleCrashWithContext should be used instead of HandleCrash in code which supports contextual logging.
func HandleCrashWithContext ¶ added in v0.31.0
func HandleCrashWithContext(ctx context.Context, additionalHandlers ...func(context.Context, interface{}))
HandleCrashWithContext simply catches a crash and logs an error. Meant to be called via defer. Additional context-specific handlers can be provided, and will be called in case of panic. HandleCrash actually crashes, after calling the handlers and logging the panic message.
E.g., you can provide one or more additional handlers for something like shutting down go routines gracefully.
The context is used to determine how to log.
func HandleError ¶
func HandleError(err error)
HandlerError is a method to invoke when a non-user facing piece of code cannot return an error and needs to indicate it has been ignored. Invoking this method is preferable to logging the error - the default behavior is to log but the errors may be sent to a remote server for analysis.
TODO(pohly): logcheck:context // HandleErrorWithContext should be used instead of HandleError in code which supports contextual logging.
func HandleErrorWithContext ¶ added in v0.31.0
func HandleErrorWithContext(ctx context.Context, err error, msg string, keysAndValues ...interface{})
HandlerErrorWithContext is a method to invoke when a non-user facing piece of code cannot return an error and needs to indicate it has been ignored. Invoking this method is preferable to logging the error - the default behavior is to log but the errors may be sent to a remote server for analysis. The context is used to determine how to log the error.
If contextual logging is enabled, the default log output is equivalent to
logr.FromContext(ctx).WithName("UnhandledError").Error(err, msg, keysAndValues...)
Without contextual logging, it is equivalent to:
klog.ErrorS(err, msg, keysAndValues...)
In contrast to HandleError, passing nil for the error is still going to trigger a log entry. Don't construct a new error or wrap an error with fmt.Errorf. Instead, add additional information via the mssage and key/value pairs.
This variant should be used instead of HandleError because it supports structured, contextual logging.
Example ¶
state := klog.CaptureState() defer state.Restore() var fs flag.FlagSet klog.InitFlags(&fs) for flag, value := range map[string]string{ "one_output": "true", "logtostderr": "false", } { if err := fs.Set(flag, value); err != nil { fmt.Printf("Unexpected error configuring klog: %v", err) return } } var buffer bytes.Buffer klog.SetOutput(&buffer) logger := klog.Background() logger = klog.LoggerWithValues(logger, "request", 42) ctx := klog.NewContext(context.Background(), logger) // The line number of the next call must be at line 60. Here are some // blank lines that can be removed to keep the line unchanged. // // // // // // HandleErrorWithContext(ctx, errors.New("fake error"), "test") klog.Flush() // Strip varying header. Code location should be constant and something // that needs to be tested. output := buffer.String() output = regexp.MustCompile(`^.* ([^[:space:]]*.go:[[:digit:]]*)\] `).ReplaceAllString(output, `xxx $1] `) fmt.Print(output)
Output: xxx runtime_stack_test.go:60] "test" err="fake error" logger="UnhandledError" request=42
func Must ¶
func Must(err error)
Must panics on non-nil errors. Useful to handling programmer level errors.
func RecoverFromPanic ¶
func RecoverFromPanic(err *error)
RecoverFromPanic replaces the specified error with an error containing the original error, and the call tree when a panic occurs. This enables error handlers to handle errors and panics the same way.