File name is not available in parser. Move error printing to writer.
authorOleksandr Gavenko <gavenkoa@gmail.com>
Sun, 27 Mar 2016 22:43:45 +0300
changeset 399 a6a7036f3c6f
parent 398 54ef571cf72a
child 400 aa03182d2e26
File name is not available in parser. Move error printing to writer.
py/gadict.py
py/gadict_c5.py
--- a/py/gadict.py	Sun Mar 27 22:36:19 2016 +0300
+++ b/py/gadict.py	Sun Mar 27 22:43:45 2016 +0300
@@ -2,13 +2,20 @@
 import regex
 
 
-class ParseException(Exception):
+class ParseException(BaseException):
 
-    def __init__(self, msg):
+    def __init__(self, msg, lineno = None, line = None):
         self.msg = msg
+        self.lineno = lineno
+        self.line = line
 
     def __repr__(self):
-        return self.msg
+        if self.lineno is None:
+            return self.msg
+        elif self.line is None:
+            return ":{:d}:{:s}".format(self.lineno, self.msg)
+        else:
+            return ":{:d}: {:s}\nLINE: {:s}".format(self.lineno, self.msg, self.line)
 
 
 class Parser:
@@ -42,9 +49,8 @@
                 self.parse_article()
         except ParseException as ex:
             if self.TRAILING_SPACES_RE.match(self.line):
-                fout.write("{:s}:{:d}: {:s}".format(fgadict, self.lineno, "Traling spaces detected...\n"))
-            fout.write("{:s}:{:d}: {:s}\nLINE: {:s}\n".format(fgadict, self.lineno, str(ex), self.line))
-            raise Exception(ex)
+                raise ParseException("Traling spaces detected...\n", self.lineno, self.line) from ex
+            raise ParseException(ex.msg, self.lineno, self.line) from ex
         return self.dom
 
     def parse_prelude(self):
--- a/py/gadict_c5.py	Sun Mar 27 22:36:19 2016 +0300
+++ b/py/gadict_c5.py	Sun Mar 27 22:43:45 2016 +0300
@@ -19,8 +19,16 @@
 
 
 parser = gadict.Parser()
-dom = parser.parse(fin)
-fin.close()
+try:
+    dom = parser.parse(fin)
+except gadict.ParseException as ex:
+    sys.stdout.write("{:s}{:s}\n".format(fgadict, repr(ex)))
+    if __debug__:
+        import traceback
+        traceback.print_exc()
+    exit(1)
+finally:
+    fin.close()
 
 for idx in range(1, len(dom)):
     article = dom[idx]