在 Python 中加载无效数据时忽略异常

不同应用程序创建的电子邮件文件并不总是遵循规范。例如,iCalendar 文件可能包含具有非法值的递归规则。默认情况下,Aspose.Email 会为此类数据抛出异常。对于其中的一些情况,库可以跳过非法部分并继续加载。

该 ExceptionManager 类位于 aspose.email.exceptions 模块控制此行为。它允许您忽略所有可忽略的异常或仅选择性的忽略。

识别可忽略的异常

当异常可以被忽略时,其消息会告知您并显示此案例的路径。例如,加载包含 RRULE:FREQ=DAILY;INTERVAL=0;COUNT=3 与 Appointment.load 抛出一个 RuntimeError 带有以下消息:

Proxy error(AsposeException): Incorrect option value of a recurrent rule: 'INTERVAL'.

If you want to ignore an exception and want to proceed further then you can use:
ExceptionManager.IgnoreList.Add(@"RecurrenceRule\IncorrectIntervalRulePart")
The INTERVAL rule part should be a positive integer.

第一行描述了问题。该 ExceptionManager.IgnoreList.Add(...) 行给出此案例在 C# 语法中的路径:在 Python 中,将相同的路径传递给 ExceptionManager.ignore_list.append。最后一行解释了在忽略异常时库的行为。

可以忽略的内容

  • 仅当消息包含 ExceptionManager.IgnoreList.Add(...) 提示可以被忽略。所有其他异常始终会被抛出,无论 ExceptionManager 设置包括参数验证,如空文件名、格式错误的电子邮件地址或缺少文件等。
  • 库当前支持以下情况:
    • iCalendar 递归规则中的非法规则部分,例如, INTERVAL=0 (路径 RecurrenceRule\IncorrectIntervalRulePart)。忽略时,非法规则部分将被删除: FREQ=DAILY;INTERVAL=0;COUNT=3 加载为 FREQ=DAILY;COUNT=3.
    • 受损的 TNEF 附件 (winmail.dat) 加载 MailMessage (路径 MailMessage\Load\DecodeTnefAttachment).
    • 读取 OLM 文件时的损坏数据头。

库的新版可能会添加更多情况。始终从异常信息中获取路径。

忽略所有可忽略的异常

调用 ExceptionManager.set_ignore_all(True) 以忽略所有可以忽略的异常。该 ExceptionManager.ignore_all 属性返回当前值且为只读。

from aspose.email.calendar import Appointment
from aspose.email.exceptions import ExceptionManager

ExceptionManager.set_ignore_all(True)

# The invalid INTERVAL rule part is dropped, the appointment is loaded
appointment = Appointment.load("event.ics")
print(appointment.recurrence)  # FREQ=DAILY;COUNT=3

忽略选定异常

若只想忽略某些情况,请将它们在异常消息中的路径添加到 ExceptionManager.ignore_list。一个入口还覆盖了以其开头的每条路径。例如, RecurrenceRule 涵盖所有循环规则情况。

from aspose.email.calendar import Appointment
from aspose.email.exceptions import ExceptionManager

ExceptionManager.ignore_list.append(r"RecurrenceRule\IncorrectIntervalRulePart")

appointment = Appointment.load("event.ics")
print(appointment.recurrence)  # FREQ=DAILY;COUNT=3

恢复默认行为

ExceptionManager 设置是静态的。它们适用于整个应用程序,直至您更改它们。要再次引发所有异常,请重置设置:

from aspose.email.exceptions import ExceptionManager

ExceptionManager.set_ignore_all(False)
ExceptionManager.ignore_list.clear()