Reputation: 4944
Lots of resources say to let the errors "bubble up" from the lower layers, but I am not sure how to achieve that in my application. Do I need to create a separate utility class for validation or other errors and listen for it at each layer?
For example, if user enters a email address and only unique email addresses are allowed, I assume that I would check for this in the business layer. When I invoke the business logic from UI, do I just include output parameters in my business classes for errors / error msgs. Should I treat handled exceptions the same as business rule exceptions?
Here is a BLL code example:
public class user()
{
public void Save(UserObject myUser, out bool result, out string resultMsg )
{
}
OR
string saveResultMsg;
public bool Save(UserObject myUser)
{
saveResultMsg = "bad data whatever";
return false;
}
}
Upvotes: 4
Views: 2350
Reputation: 48675
For example, if user enters a email address and only unique email addresses are allowed, I assume that I would check for this in the business layer. When I invoke the business logic from UI, do I just include output parameters in my business classes for errors / error msgs. Should I treat handled exceptions the same as business rule exceptions?
I prefer to provide a method the application layer can use to check uniqueness, then check again in the business layer and throw an exception if the caller attempts to save a duplicate value.
Unless the two database calls actually cause performance problems, I usually find that separating the command and query logic is worth it.
(I'm giving this advice with respect to business applications, most of which have modest performance requirements. There are many other types of software for which this approach isn't always - or ever - appropriate.)
Upvotes: 2
Reputation: 245499
You could always create Custom Exceptions for your application, have your Business Layer throw those Exceptions when an error occurs, and then have your UI/Consumer properly handle those Custom Exceptions.
In your case, I would probably do something like:
[Serializable]
public class EmailValidationException : Exception
{
// overriden constructors would go here
private List<string> _validationMessages = new List<string>();
// store your validation exception messages in a collection
public ReadOnlyCollection<string> ValidationMessages
{
get
{
return _validationMessages.AsReadOnly();
}
}
}
Upvotes: 0
Reputation: 63136
This really depends on what you are looking to do, ideally an exception should be used for exceptional circumstances and not to control the process flow.
I'm a fan of an internal validation process and having a Boolean "Save" method. If false, you can check a "Validation Exceptions" property to see what the rules were that were violated for the entry to not save.
You could also use exceptions if needed, just be sure to use an appropriate exception type and NOT the base Exception class.
Upvotes: 3