Debian Codegraph @

gavo/user/errhandle.py

raw
1 """
2 Common error handling facilities for user interface components.
3 """
4
5 #c Copyright 2008-2025, the GAVO project <[email protected]>
6 #c
7 #c This program is free software, covered by the GNU GPL. See the
8 #c COPYING file in the source distribution.
9
10
11 import re
12 import sys
13 import textwrap
14 import traceback
15
16 from gavo import base
17 from gavo import utils
18 from gavo.base import sqlsupport
19
20
21 class _Reformatter(object):
22 """A helper class for reformatMessage.
23 """
24 verbatimRE = re.compile(r"\s")
25
26 def __init__(self):
27 self.inBuffer, self.outBuffer = [], []
28
29 def flush(self):
30 if self.inBuffer:
31 self.outBuffer.append(textwrap.fill("\n".join(self.inBuffer),
32 break_long_words=False))
33 self.inBuffer = []
34
35 def feed(self, line):
36 if self.verbatimRE.match(line):
37 self.flush()
38 self.outBuffer.append(line)
39 elif not line.strip():
40 self.flush()
41 self.outBuffer.append("")
42 else:
43 self.inBuffer.append(line)
44
45 def get(self):
46 self.flush()
47 return "\n".join(self.outBuffer)
48
49 def feedLines(self, lines):
50 for l in lines:
51 self.feed(l)
52
53
54 def reformatMessage(msg):
55 """reflows a message to about 80 characters width.
56
57 Lines starting with whitespace will not be wrapped.
58 """
59 r = _Reformatter()
60 r.feedLines(msg.split("\n"))
61 return r.get()
62
63
64 def outputError(message):
65 if isinstance(message, bytes):
66 # make sure we don't fail on non-ASCII in byte strings
67 message = message.decode("ascii", "replace")
68 sys.stderr.write(message)
69
70
71 def formatRow(aDict):
72 """returns a string representation of aDict.
73
74 I'm trying to make this palatable for error message output.
75 """
76 res = []
77 for key, value in sorted(aDict.items()):
78 res.append("%s -> %s"%(key, repr(value)))
79 return "\n ".join(res)
80
81
82 def raiseAndCatch(opts=None, output=outputError):
83 """Tries to come up with a good error message for the current exception.
84
85 opts can be an object with some attribute (read the source); this
86 usually comes from user.cli's main.
87
88 output must be a function accepting a single string, defaulting to
89 something just encoding the string for the output found and dumping
90 it to stderr.
91
92 The function returns a suggested return value for the whole program.
93 """
94 # Messages are reformatted by reformatMessage (though it's probably ok
95 # to just call output(someString) to write to the user directly.
96 #
97 # To write messages, append strings to the messages list. An empty string
98 # would produce a paragraph. Append unicode or ASCII.
99 retval = 1
100 messages = []
101
102 _, msg, _ = sys.exc_info()
103
104 if isinstance(msg, SystemExit):
105 return msg.code
106
107 elif isinstance(msg, KeyboardInterrupt):
108 return 2
109
110 elif isinstance(msg, base.SourceParseError):
111 messages.append("While parsing source %s, near %s:\n"%(
112 msg.source, msg.location))
113 messages.append((msg.msg+"\n"))
114 if msg.offending:
115 messages.append("Offending literal: %s\n"%repr(msg.offending))
116
117 elif isinstance(msg, base.BadCode):
118 messages.append("Bad user %s: %s\n"%(msg.codeType, str(msg.origExc)))
119 if msg.pos:
120 messages.append("(At %s)"%msg.pos)
121 if base.DEBUG:
122 sys.stderr.write("The code that produced the error is:\n%s\n\n"%
123 msg.code)
124
125 elif isinstance(msg, base.DBTableError):
126 messages.append("While building table %s: %s"%(msg.qName,
127 msg))
128
129 elif isinstance(msg, base.MetaError):
130 messages.append("While working on metadata of '%s': %s"%(
131 str(msg.carrier or "RD global"),
132 str(msg.__class__.__name__)))
133 if getattr(msg, "pos", None):
134 messages.append("in element starting at %s:"%msg.pos)
135 if msg.key is not None:
136 messages.append("-- key %s --"%msg.key)
137 messages.append(utils.safe_str(msg))
138
139 elif isinstance(msg, (base.ValidationError, base.ReportableError,
140 base.LiteralParseError, base.StructureError, base.NotFoundError,
141 base.MetaValidationError)):
142 if not getattr(msg, "posInMsg", False):
143 if getattr(msg, "pos", None):
144 messages.append("At or near %s:"%msg.pos)
145 elif getattr(msg, "inFile", None):
146 messages.append("In %s:"%msg.inFile)
147
148 if getattr(msg, "row", None):
149 row = dict((key, value) for key, value in msg.row.items()
150 if key and not key.startswith("_") and not key.endswith("_"))
151 messages.append(" Row\n %s"%formatRow(row))
152 messages.append(" ")
153 messages.append(str(msg))
154
155 elif isinstance(msg, base.DataError):
156 messages.append("Error in input data:")
157 messages.append(utils.safe_str(msg))
158
159 elif isinstance(msg, sqlsupport.ProgrammingError):
160 if msg.cursor:
161 messages.append("While executing DB query:\n")
162 messages.append(" "+utils.debytify(msg.cursor.query))
163 messages.append("\nThe database engine reported:\n")
164 messages.append(" "+utils.debytify(msg.pgerror or msg.args[0]))
165
166 else:
167 if hasattr(msg, "excRow"):
168 messages.append("Snafu in %s, %s\n"%(msg.excRow, msg.excCol))
169 messages.append("")
170 messages.append("Oops. Unhandled exception %s.\n"%msg.__class__.__name__)
171 messages.append("Exception payload: %s"%utils.safe_str(msg))
172 base.ui.notifyError(f"Uncaught exception at toplevel: {msg}")
173
174 if getattr(opts, "enablePDB", False):
175 raise
176 elif getattr(opts, "alwaysTracebacks", False):
177 traceback.print_exc()
178
179 if messages:
180 errTx = utils.safe_str("*** Error: "+"\n".join(messages))
181 output(reformatMessage(errTx)+"\n")
182 if getattr(opts, "showHints", True) and getattr(msg, "hint", None):
183 output(reformatMessage("Hint: "+msg.hint)+"\n")
184
185 return retval
186
187
188 def bailOut():
189 """A fake cli operation just raising exceptions.
190
191 This is mainly for testing and development.
192 """
193 if len(sys.argv)<2:
194 raise ValueError("Too short")
195 arg = sys.argv[1]
196 if arg=="--help":
197 raise base.Error("Hands off this. For Developers only")