Debian Codegraph @

modules/caddyhttp/errors.go

raw symbols SCIP
1 // Copyright 2015 Matthew Holt and The Caddy Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package caddyhttp
16
17 import (
18 "errors"
19 "fmt"
20 weakrand "math/rand/v2"
21 "path"
22 "runtime"
23 "strings"
24
25 "github.com/caddyserver/caddy/v2"
26 )
27
28 // Error is a convenient way for a Handler to populate the
29 // essential fields of a HandlerError. If err is itself a
30 // HandlerError, then any essential fields that are not
31 // set will be populated.
32 func Error(statusCode int, err error) HandlerError {
33 const idLen = 9
34 var he HandlerError
35 if errors.As(err, &he) {
36 if he.ID == "" {
37 he.ID = randString(idLen, true)
38 }
39 if he.Trace == "" {
40 he.Trace = trace()
41 }
42 if he.StatusCode == 0 {
43 he.StatusCode = statusCode
44 }
45 return he
46 }
47 return HandlerError{
48 ID: randString(idLen, true),
49 StatusCode: statusCode,
50 Err: err,
51 Trace: trace(),
52 }
53 }
54
55 // HandlerError is a serializable representation of
56 // an error from within an HTTP handler.
57 type HandlerError struct {
58 Err error // the original error value and message
59 StatusCode int // the HTTP status code to associate with this error
60
61 ID string // generated; for identifying this error in logs
62 Trace string // produced from call stack
63 }
64
65 func (e HandlerError) Error() string {
66 var s string
67 if e.ID != "" {
68 s += fmt.Sprintf("{id=%s}", e.ID)
69 }
70 if e.Trace != "" {
71 s += " " + e.Trace
72 }
73 if e.StatusCode != 0 {
74 s += fmt.Sprintf(": HTTP %d", e.StatusCode)
75 }
76 if e.Err != nil {
77 s += ": " + e.Err.Error()
78 }
79 return strings.TrimSpace(s)
80 }
81
82 // Unwrap returns the underlying error value. See the `errors` package for info.
83 func (e HandlerError) Unwrap() error { return e.Err }
84
85 // randString returns a string of n random characters.
86 // It is not even remotely secure OR a proper distribution.
87 // But it's good enough for some things. It excludes certain
88 // confusing characters like I, l, 1, 0, O, etc. If sameCase
89 // is true, then uppercase letters are excluded.
90 func randString(n int, sameCase bool) string {
91 if n <= 0 {
92 return ""
93 }
94 dict := []byte("abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY23456789")
95 if sameCase {
96 dict = []byte("abcdefghijkmnpqrstuvwxyz0123456789")
97 }
98 b := make([]byte, n)
99 for i := range b {
100 //nolint:gosec
101 b[i] = dict[weakrand.IntN(len(dict))]
102 }
103 return string(b)
104 }
105
106 func trace() string {
107 if pc, file, line, ok := runtime.Caller(2); ok {
108 filename := path.Base(file)
109 pkgAndFuncName := path.Base(runtime.FuncForPC(pc).Name())
110 return fmt.Sprintf("%s (%s:%d)", pkgAndFuncName, filename, line)
111 }
112 return ""
113 }
114
115 // ErrorCtxKey is the context key to use when storing
116 // an error (for use with context.Context).
117 const ErrorCtxKey = caddy.CtxKey("handler_chain_error")