forked from tliron/py4go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexception.go
82 lines (67 loc) · 1.41 KB
/
exception.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
package python
// See:
// https://docs.python.org/3/c-api/exceptions.html
import (
"errors"
)
/*
#define PY_SSIZE_T_CLEAN
#include <Python.h>
*/
import "C"
func HasException() bool {
return C.PyErr_Occurred() != nil
}
func GetError() error {
if exception := FetchException(); exception != nil {
return exception
} else {
return errors.New("Python error without an exception")
}
}
//
// Exception
//
type Exception struct {
Type *Reference
Value *Reference
Traceback *Reference
}
func FetchException() *Exception {
var type_, value, traceback *C.PyObject
C.PyErr_Fetch(&type_, &value, &traceback)
if type_ != nil {
defer C.PyErr_Restore(type_, value, traceback)
var type__, value_, traceback_ *Reference
if type_ != nil {
type__ = NewReference(type_)
}
if value != nil {
value_ = NewReference(value)
}
if traceback != nil {
traceback_ = NewReference(traceback)
}
return NewExceptionRaw(type__, value_, traceback_)
} else {
return nil
}
}
func NewExceptionRaw(type_ *Reference, value *Reference, traceback *Reference) *Exception {
return &Exception{
Type: type_,
Value: value,
Traceback: traceback,
}
}
// error signature
func (self *Exception) Error() string {
// TODO: include traceback?
if self.Value != nil {
return self.Value.String()
} else if self.Type != nil {
return self.Type.String()
} else {
return "malformed Python exception"
}
}