-
Notifications
You must be signed in to change notification settings - Fork 885
/
error.go
143 lines (109 loc) · 2.37 KB
/
error.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
// Copyright 2011 The Walk Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build windows
package walk
import (
"fmt"
"log"
"runtime/debug"
)
import (
"github.com/lxn/win"
)
var (
logErrors bool
panicOnError bool
)
type Error struct {
inner error
message string
stack []byte
}
func (err *Error) Inner() error {
return err.inner
}
func (err *Error) Message() string {
if err.message != "" {
return err.message
}
if err.inner != nil {
if walkErr, ok := err.inner.(*Error); ok {
return walkErr.Message()
} else {
return err.inner.Error()
}
}
return ""
}
func (err *Error) Stack() []byte {
return err.stack
}
func (err *Error) Error() string {
return fmt.Sprintf("%s\n\nStack:\n%s", err.Message(), err.stack)
}
func processErrorNoPanic(err error) error {
if logErrors {
if walkErr, ok := err.(*Error); ok {
log.Print(walkErr.Error())
} else {
log.Printf("%s\n\nStack:\n%s", err, debug.Stack())
}
}
return err
}
func processError(err error) error {
processErrorNoPanic(err)
if panicOnError {
panic(err)
}
return err
}
func newErr(message string) error {
return &Error{message: message, stack: debug.Stack()}
}
func newError(message string) error {
return processError(newErr(message))
}
func newErrorNoPanic(message string) error {
return processErrorNoPanic(newErr(message))
}
func lastError(win32FuncName string) error {
if errno := win.GetLastError(); errno != win.ERROR_SUCCESS {
return newError(fmt.Sprintf("%s: Error %d", win32FuncName, errno))
}
return newError(win32FuncName)
}
func errorFromHRESULT(funcName string, hr win.HRESULT) error {
return newError(fmt.Sprintf("%s: Error %d", funcName, hr))
}
func wrapErr(err error) error {
if _, ok := err.(*Error); ok {
return err
}
return &Error{inner: err, stack: debug.Stack()}
}
func wrapErrorNoPanic(err error) error {
return processErrorNoPanic(wrapErr(err))
}
func wrapError(err error) error {
return processError(wrapErr(err))
}
func toErrorNoPanic(x interface{}) error {
switch x := x.(type) {
case *Error:
return x
case error:
return wrapErrorNoPanic(x)
case string:
return newErrorNoPanic(x)
}
return newErrorNoPanic(fmt.Sprintf("Error: %v", x))
}
func toError(x interface{}) error {
err := toErrorNoPanic(x)
if panicOnError {
panic(err)
}
return err
}