Skip to content
Myr

exceptions.py

This file

Path

src/jinja2/exceptions.py

177 lines · 5.3 KiB · Python

Last changed by

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

History of this file

Take it

1# -*- coding: utf-8 -*-2from ._compat import imap3from ._compat import implements_to_string4from ._compat import PY25from ._compat import text_type678class TemplateError(Exception):9    """Baseclass for all template errors."""1011    if PY2:1213        def __init__(self, message=None):14            if message is not None:15                message = text_type(message).encode("utf-8")16            Exception.__init__(self, message)1718        @property19        def message(self):20            if self.args:21                message = self.args[0]22                if message is not None:23                    return message.decode("utf-8", "replace")2425        def __unicode__(self):26            return self.message or u""2728    else:2930        def __init__(self, message=None):31            Exception.__init__(self, message)3233        @property34        def message(self):35            if self.args:36                message = self.args[0]37                if message is not None:38                    return message394041@implements_to_string42class TemplateNotFound(IOError, LookupError, TemplateError):43    """Raised if a template does not exist.4445    .. versionchanged:: 2.1146        If the given name is :class:`Undefined` and no message was47        provided, an :exc:`UndefinedError` is raised.48    """4950    # looks weird, but removes the warning descriptor that just51    # bogusly warns us about message being deprecated52    message = None5354    def __init__(self, name, message=None):55        IOError.__init__(self, name)5657        if message is None:58            from .runtime import Undefined5960            if isinstance(name, Undefined):61                name._fail_with_undefined_error()6263            message = name6465        self.message = message66        self.name = name67        self.templates = [name]6869    def __str__(self):70        return self.message717273class TemplatesNotFound(TemplateNotFound):74    """Like :class:`TemplateNotFound` but raised if multiple templates75    are selected.  This is a subclass of :class:`TemplateNotFound`76    exception, so just catching the base exception will catch both.7778    .. versionchanged:: 2.1179        If a name in the list of names is :class:`Undefined`, a message80        about it being undefined is shown rather than the empty string.8182    .. versionadded:: 2.283    """8485    def __init__(self, names=(), message=None):86        if message is None:87            from .runtime import Undefined8889            parts = []9091            for name in names:92                if isinstance(name, Undefined):93                    parts.append(name._undefined_message)94                else:95                    parts.append(name)9697            message = u"none of the templates given were found: " + u", ".join(98                imap(text_type, parts)99            )100        TemplateNotFound.__init__(self, names and names[-1] or None, message)101        self.templates = list(names)102103104@implements_to_string105class TemplateSyntaxError(TemplateError):106    """Raised to tell the user that there is a problem with the template."""107108    def __init__(self, message, lineno, name=None, filename=None):109        TemplateError.__init__(self, message)110        self.lineno = lineno111        self.name = name112        self.filename = filename113        self.source = None114115        # this is set to True if the debug.translate_syntax_error116        # function translated the syntax error into a new traceback117        self.translated = False118119    def __str__(self):120        # for translated errors we only return the message121        if self.translated:122            return self.message123124        # otherwise attach some stuff125        location = "line %d" % self.lineno126        name = self.filename or self.name127        if name:128            location = 'File "%s", %s' % (name, location)129        lines = [self.message, "  " + location]130131        # if the source is set, add the line to the output132        if self.source is not None:133            try:134                line = self.source.splitlines()[self.lineno - 1]135            except IndexError:136                line = None137            if line:138                lines.append("    " + line.strip())139140        return u"\n".join(lines)141142    def __reduce__(self):143        # https://bugs.python.org/issue1692335 Exceptions that take144        # multiple required arguments have problems with pickling.145        # Without this, raises TypeError: __init__() missing 1 required146        # positional argument: 'lineno'147        return self.__class__, (self.message, self.lineno, self.name, self.filename)148149150class TemplateAssertionError(TemplateSyntaxError):151    """Like a template syntax error, but covers cases where something in the152    template caused an error at compile time that wasn't necessarily caused153    by a syntax error.  However it's a direct subclass of154    :exc:`TemplateSyntaxError` and has the same attributes.155    """156157158class TemplateRuntimeError(TemplateError):159    """A generic runtime error in the template engine.  Under some situations160    Jinja may raise this exception.161    """162163164class UndefinedError(TemplateRuntimeError):165    """Raised if a template tries to operate on :class:`Undefined`."""166167168class SecurityError(TemplateRuntimeError):169    """Raised if a template tries to do something insecure if the170    sandbox is enabled.171    """172173174class FilterArgumentError(TemplateRuntimeError):175    """This error is raised if a filter was called with inappropriate176    arguments177    """