github.com/cockroachdb/cockroachdb-parser@v0.23.3-0.20240213214944-911057d40c9a/pkg/sql/pgwire/pgerror/severity.go (about) 1 // Copyright 2020 The Cockroach Authors. 2 // 3 // Use of this software is governed by the Business Source License 4 // included in the file licenses/BSL.txt. 5 // 6 // As of the Change Date specified in that file, in accordance with 7 // the Business Source License, use of this software will be governed 8 // by the Apache License, Version 2.0, included in the file 9 // licenses/APL.txt. 10 11 package pgerror 12 13 import ( 14 "context" 15 "fmt" 16 17 "github.com/cockroachdb/errors" 18 "github.com/gogo/protobuf/proto" 19 ) 20 21 // DefaultSeverity is the default severity for decoding severity of errors. 22 const DefaultSeverity = "ERROR" 23 24 // WithSeverity decorates the error with a severity. 25 func WithSeverity(err error, severity string) error { 26 if err == nil { 27 return nil 28 } 29 30 return &withSeverity{cause: err, severity: severity} 31 } 32 33 // GetSeverity attempts to unwrap and find a Severity. 34 func GetSeverity(err error) string { 35 if c := (*withSeverity)(nil); errors.As(err, &c) { 36 return c.severity 37 } 38 return DefaultSeverity 39 } 40 41 // withSeverity decorates an error with a given severity. 42 type withSeverity struct { 43 cause error 44 severity string 45 } 46 47 var _ error = (*withSeverity)(nil) 48 var _ errors.SafeDetailer = (*withSeverity)(nil) 49 var _ fmt.Formatter = (*withSeverity)(nil) 50 var _ errors.Formatter = (*withSeverity)(nil) 51 52 func (w *withSeverity) Error() string { return w.cause.Error() } 53 func (w *withSeverity) Cause() error { return w.cause } 54 func (w *withSeverity) Unwrap() error { return w.cause } 55 func (w *withSeverity) SafeDetails() []string { return []string{w.severity} } 56 57 func (w *withSeverity) Format(s fmt.State, verb rune) { errors.FormatError(w, s, verb) } 58 59 func (w *withSeverity) FormatError(p errors.Printer) (next error) { 60 if p.Detail() { 61 p.Printf("severity: %s", w.severity) 62 } 63 return w.cause 64 } 65 66 // decodeWithSeverity is a custom decoder that will be used when decoding 67 // withSeverity error objects. 68 // Note that as the last argument it takes proto.Message (and not 69 // protoutil.Message which is required by linter) because the latter brings in 70 // additional dependencies into this package and the former is sufficient here. 71 func decodeWithSeverity( 72 _ context.Context, cause error, _ string, details []string, _ proto.Message, 73 ) error { 74 severity := DefaultSeverity 75 if len(details) > 0 { 76 severity = details[0] 77 } 78 return &withSeverity{cause: cause, severity: severity} 79 } 80 81 func init() { 82 errors.RegisterWrapperDecoder(errors.GetTypeKey((*withSeverity)(nil)), decodeWithSeverity) 83 }