Django: Should custom template simple tags raise exception or fail silently?

606 Views Asked by At

I have tried to find answer to this question from the official docs, but all that I could find is:

render() should never raise TemplateSyntaxError or any other exception. It should fail silently, just as template filters should

But the above doesn't really answer the question and, perhaps, has confused me even more, because it applies to regular custom tags, and my concern is with simple tags.

Here is an example (and the question itself):

@register.simple_tag
def foo(formfield):
    if isinstance(formfield, forms.ChoiceField):
      # do something
    else:
      # This function doesn't deal with non-ChoiceField. 
      # Should it raise exception or fail silently?

If your answer is to raise exception, would it be TemplateSyntaxError or other exception?

2

There are 2 best solutions below

1
Brandon Taylor On BEST ANSWER

I think the answer is that "it depends on what's right for your app". If you need or want to code defensively, raise an exception. If there's a valid business reason to raise an exception because something won't get displayed, like a price or something, then raise an exception, or at least a Warning.

Otherwise, just let it do nothing and be happy that you're not looking at a .NET MVC stack trace :)

0
Filip Dupanović On

Template tags should always raise an exception if they cannot produce valid output. While you can raise a custom exception, make sure that it extends TemplateSyntaxError--this ensures that the exception is immediately caught by the template parser; you'll have access to all the necessary inputs to drill down on the problem.