python - Graceful error handling and logging in Jinja extension -
i'm developing jinja extension performs few potentially harmful operations, on failure raise exception holds information on went wrong.
when occurs, of course exception prevent jinja completing render process , return none
rather render result. problem mitigated using try/catch statement , returning empty string or whatever suitable.
however, throws away exception , debugging info, rather pass on error log. system responsible setting jinja environment has it's own logging service, prefer keep decoupled extension. aware though, jinja has undefined
class have used intercept access of undefined variables in project.
is there way raise special type of exception (undefinedexception
did not work), or tell jinja environment log warning, when error occurs in extension, while still allowing continue execution?
what have in mind along lines of example:
def _render(*args, **kwrags): # ... try: self.potentially_harmful_operation() except exception e: self.environment.warning(e) return markup("") # ... return markup('<img src"{}">'.format(img_path))
so, clarify, wrote in comment below:
fundamentally guess question boils down "how can make jinja produce warning, e.g. missing variables".
for interested, managed solve implementing own undefined
class (largely inspired make_logging_undefined
, supplying environment using undefined
keyword. depending on needs, default make_logging_undefined
might suffice.
once that's in place, trick emit warning in environment. done instantiating environment's undefined
, executing 1 of magic methods (e.g. __str__
). hooking on example code above, accomplished this:
def _render(*args, **kwrags): # ... try: self.potentially_harmful_operation() except exception e: str(self.environment.undefined(e)) return markup("") # ... return markup('<img src"{}">'.format(img_path))
Comments
Post a Comment