Reputation: 656
I want to throw an exception to say that we have an invalid email address as I dont want to proceed until we get a valid email address. Is this where I want to do it and if so, how?
void Engine_AfterReadRecord(EngineBase engine, FileHelpers.Events.AfterReadEventArgs<UserInfoFromAd> e){
bool isEmailValid = IsEmailValid(e.Record.Email);
if (!isEmailValid){
//I want to throw exception
}
}
Upvotes: 2
Views: 2320
Reputation: 11326
Throwing the exception in the AfterReadRecord
event is fine, but you need to set the ErrorMode
to SaveAndContinue
. This tells the engine to save the error to Engine.ErrorManager.Errors
and continue importing. After the import you can process the errors.
Here is an example program:
[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");
}
}
}
Upvotes: 3
Reputation: 35255
What seems to be the problem? Just throw it:
if (!isEmailValid)
{
throw new InvalidDataException("Email is not valid.");
}
Upvotes: 1