Skip to content

Commit ae49c80

Browse files
authored
Merge pull request #7 from WnP/handling_exceptions
Handling exceptions during rendering
2 parents a22f312 + 73e98c2 commit ae49c80

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

djangomako/backends.py

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
from django.utils.module_loading import import_string
2222

2323
from mako.template import Template as MakoTemplate
24+
from mako.exceptions import RichTraceback
2425
from mako import exceptions as mako_exceptions
2526

2627

@@ -164,7 +165,38 @@ def render(self, context=None, request=None):
164165
context['csrf_input'] = csrf_input_lazy(request)
165166
context['csrf_token'] = csrf_token_lazy(request)
166167

167-
return self.template.render(**context)
168+
try:
169+
return self.template.render(**context)
170+
except Exception as e:
171+
traceback = RichTraceback()
172+
173+
source = traceback.source
174+
if not source:
175+
# There's no template source lines then raise
176+
raise e
177+
178+
source = source.split('\n')
179+
line = traceback.lineno
180+
top = max(0, line - 4)
181+
bottom = min(len(source), line + 5)
182+
source_lines = [(i + 1, source[i]) for i in range(top, bottom)]
183+
184+
e.template_debug = {
185+
'name': traceback.records[5][4],
186+
'message': '{}: {}'.format(
187+
traceback.errorname, traceback.message),
188+
'source_lines': source_lines,
189+
'line': line,
190+
'during': source_lines[line - top - 1][1],
191+
'total': bottom - top,
192+
'bottom': bottom,
193+
'top': top + 1,
194+
# mako's RichTraceback doesn't return column number
195+
'before': '',
196+
'after': '',
197+
}
198+
199+
raise e
168200

169201
@staticmethod
170202
def get_reverse_url():

0 commit comments

Comments
 (0)