2

我想抛出一个异常,说我们有一个无效的电子邮件地址,因为我不想继续,直到我们得到一个有效的电子邮件地址。这是我想做的地方吗?如果是,怎么做?

void Engine_AfterReadRecord(EngineBase engine, FileHelpers.Events.AfterReadEventArgs<UserInfoFromAd> e){
     bool isEmailValid = IsEmailValid(e.Record.Email);
     if (!isEmailValid){
        //I want to throw exception
     }
 }
4

2 回答 2

3

AfterReadRecord事件中抛出异常很好,但您需要ErrorModeSaveAndContinue. 这告诉引擎将错误保存到Engine.ErrorManager.Errors并继续导入。导入后,您可以处理错误。

这是一个示例程序:

[DelimitedRecord("|")]
public class MyClass
{
    public string Field1 { get; set; }
    public int Field2 { get; set; }
    public string Email { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var engine = new FileHelperEngine<MyClass>();
        engine.AfterReadRecord += new FileHelpers.Events.AfterReadHandler<MyClass>(engine_AfterReadRecord);
        engine.ErrorMode = ErrorMode.SaveAndContinue;
        // import a record with an invalid Email
        MyClass[] validRecords = engine.ReadString("Hello|23|World");
        ErrorInfo[] errors = engine.ErrorManager.Errors;
        Assert.AreEqual(1, engine.TotalRecords); // 1 record was processed
        Assert.AreEqual(0, validRecords.Length); // 0 records were valid
        Assert.AreEqual(1, engine.ErrorManager.ErrorCount); // 1 error was found
        Assert.That(errors[0].ExceptionInfo.Message == "Email is invalid");
    }

    static bool IsEmailValid(string email)
    {
        return false;
    }

    static void engine_AfterReadRecord(EngineBase engine, FileHelpers.Events.AfterReadEventArgs<MyClass> e)
    {
        bool isEmailValid = IsEmailValid(e.Record.Email);
        if (!isEmailValid)
        {
            throw new Exception("Email is invalid");
        }
    }
}
于 2012-03-29T13:39:34.387 回答
1

似乎是什么问题?扔掉它:

if (!isEmailValid)
{
    throw new InvalidDataException("Email is not valid.");
}
于 2012-03-29T02:43:12.903 回答