1

如果 TuesPechkin 为 PDF 生成的网页返回 HTTP 错误 404 或 500,我想抛出异常。我不想为看起来友好的 HTML 错误页面获取 PDF 文件。

它已经尝试了 EventHandler(参见下面的代码),但它们都没有捕获错误代码或错误消息。唯一一次引发 ErrorEvent 是当我传入一个带有虚假域名的 URL 时,例如http://www.google.bogus

Pechkin 在 SynchronizedPechkin 中具有名为“HttpErrorCode”的类属性。TuesPechkin 在哪里?

public ActionResult Index()
{
    var messages = new StringBuilder();

    IConverter converter =
        new ThreadSafeConverter(
            new RemotingToolset<PdfToolset>(
                new Win64EmbeddedDeployment(
                    new TempFolderDeployment())));

    var obj = new ObjectSettings();
    obj.PageUrl = "http://www.google.com/dummy";

    var doc = new HtmlToPdfDocument();
    doc.Objects.Add(obj);

    converter.Error += new EventHandler<ErrorEventArgs>(converter_Error);
    converter.Warning += new EventHandler<WarningEventArgs>(converter_Warning);
    converter.PhaseChange += new EventHandler<PhaseChangeEventArgs>(converter_PhaseChange);
    converter.Begin += new EventHandler<BeginEventArgs>(converter_Begin);

    byte[] pdfBinary = null;
    try
    {
        pdfBinary = converter.Convert(doc);
    }
    catch (Exception e)
    {
        messages.AppendLine(e.Message);
    }
    finally
    {
        converter.Error -= new EventHandler<ErrorEventArgs>(converter_Error);
        converter.Warning -= new EventHandler<WarningEventArgs>(converter_Warning);
        converter.PhaseChange -= new EventHandler<PhaseChangeEventArgs>(converter_PhaseChange);
        converter.Begin -= new EventHandler<BeginEventArgs>(converter_Begin);
    }

    if (messages.Length > 0)
    {
        throw new ApplicationException(messages.ToString());
    }
    return File(pdfBinary, "application/pdf");
}


void converter_Begin(object send, BeginEventArgs e)
{
    messages.AppendLine(e.ToString());
}

void converter_PhaseChange(object send, PhaseChangeEventArgs e)
{
    messages.AppendLine(e.PhaseDescription);
}

void converter_Warning(object send, WarningEventArgs e)
{
    messages.AppendLine(e.WarningMessage);
}

void converter_Error(object sender, ErrorEventArgs e)
{
    messages.AppendLine(e.ErrorMessage);
}
4

0 回答 0