ValidationError 或 TypeError、ValueError - 异常

ValidationError or TypeError, ValueError - Exceptions

我对如何在 python 中捕获异常一窍不通。我对这两种捕获异常的方法有疑问。我只找到了有关 here

的有关 ValidationError 的有用信息

但我不太明白它是否可以在 django 之外使用,或者我可以预期的关于它的错误消息是什么。我看到了这个关于类型验证的代码示例。

except (TypeError, ValueError) as error:
            LOGGER.error('Error e.g.', exc_info=True)

except ValidationError:
            LOGGER.error('Error e.g', exc_info=True)

所以对于 TypeErrorValueError 对我来说,很明显:

异常值错误

当操作或函数接收到具有正确类型但值不合适的参数时引发,并且这种情况没有用更精确的异常(例如 IndexError)来描述。

异常类型错误

当操作或函数应用于不适当类型的对象时引发。关联值是一个字符串,提供有关类型不匹配的详细信息。

总之, 我试图了解使用 ValidationError 的第二个代码的优势是什么,但它可能很棘手,因为我没有找到好的文档。如果有人可以分享有关 ValidationError 的知识,我将不胜感激,

我提出这个问题是因为我要使用相关的库,我还没有看到这样处理的异常。

https://pypi.org/project/related/

感谢社区!

它们是处理不同异常的不同代码块。

但是在这个例子中,两种情况在如何处理每个异常方面都具有相同的逻辑。

如果我们将案例分成 3 个不同的代码块可能更有意义:

except TypeError as error:
    LOGGER.error('Type error: ', exc_info=True);
except ValueError as error:
    LOGGER.error('Value error: ', exc_info=True);
except ValidationError error:
    LOGGER.error('Validation error: ', exc_info=True);

TypeError 使用错误类型时会抛出

ValueError 当使用不正确的值时会抛出

ValidationError验证失败会抛出

程序将以不同方式处理每个异常

Python异常可以这样捕获:

try:
<your code>
except <Exception>:
    <CODE 2>

或 像这样

try:
    <your code>
except(<exception1>,<exception2>):
    <Code to handle exception>

You are simply handling multiple exceptions together. You can always split them. They are not 2 different ways. In your case the as is for logging it .

这里有几个例子:

try:
    <code>
except TypeError:
    <Code for handling exception>
except ValueError:
    <Code for handling exception>
except ValidationError:
    <Code for handling exception>
except:
    <Code for handling exception>

在最后一种情况下,它捕获任何类型的异常,因为没有指定类型。
在 Python 中,程序可以引发任何异常。
事实上异常只是一个特殊的class,即使你可以为你的库创建一个。

So the best way to find about the exception is to read the docs of the library not the exception class.

如果您的程序捕获到异常并需要有关它的更多详细信息以创建日志文件,则可以这样编写代码。

except TypeError as e:
    i=str(e)

在这种情况下,您正在捕获异常并将其详细信息转换为字符串。
这是来自 Django 文档,关于您正在谈论的错误。

Form validation happens when the data is cleaned. If you want to customize this process, there are various places to make changes, each one serving a different purpose. Three types of cleaning methods are run during form processing. These are normally executed when you call the is_valid() method on a form. There are other things that can also trigger cleaning and validation (accessing the errors attribute or calling full_clean() directly), but normally they won’t be needed.

In general, any cleaning method can raise ValidationError if there is a problem with the data it is processing, passing the relevant information to the ValidationError constructor. See below for the best practice in raising ValidationError. If no ValidationError is raised, the method should return the cleaned (normalized) data as a Python object.

一些进一步的参考资料:

The link to docs
This link has info about other common builtin exception classes.