Exception handling in Model/Controller MVC - spring

I've just recently started learning MVC patterns, originally in android but currently with spring MVC framework. I'm wondering if it is more appropriate to have testing/exception handling in the model or a controller. What I mean is, say I had some field in the model which should be restricted to some values, or a range of values; should I be testing the inputs and throwing exception in the model and having the controller catch them, or should the controller check inputs on it's own before forwarding inputs to the model?
My concern with testing in the controller is that I may need to check values in several spots whereas if I were to test in the model it's only done in one place. My concern with checking inputs in the model is that, for some reason, that seems really odd to me; then again I am new to this pattern so I don't really know yet.
What is the norm? What is recommended?
Thanks everyone

It is appropriate to have testing and/or exception handling in the model and the controller, which ever is most appropriate to the handling of the exception.
For example, if you want want to parse a number from a string and use a default value when the string does not contain a number and you are parsing in the model, then you should handle the numberformatexception in the model.
I think of this as an "expected" exception.
private String blammyValue;
public int getBlammyAsInt()
{
int returnValue;
try
{
returnValue = Integer.parseInt(blammyValue);
}
catch (NumberFormatException exception)
{
returnValue = -1; // some default value
}
return returnValue;
}
If the exception is something that is out-of-the-ordinary,
like a database exception,
and for which there is no reasonable default behavior,
then catching it in the controller makes sense.

Related

Missing HttpParameterBinding and ParameterBindingAttribute

I'm investigating Web Api in ASP.NET vNext using the daily builds. In a web api 2x project, I use HttpParameterBinding and ParameterBindingAttribute in some situations (see http://bit.ly/1sxAxdk); however, I can't seem to find either in vNext. Do/will these classes exist? If not, what are my alternatives?
Edit (1-22-15):
I want to be able to serialize a complex JS object to a JSON string, put the JSON string in a hidden form field (say name="data"), submit the form, and then bind my parameter to that JSON object on the server. This will never be done by a human, but rather by a machine. I also want this very same mechanism to work if the JSON is sent directly in the request body instead of form data. I also need this to work for several different types of objects.
I've been able to accomplish this scenario in Web Api 2.2 in a few different ways, including a custom ModelBinder; however, I remember reading an MSFT blog post that suggested to use a ModelBinder for query string binding, formatters for request body, and HttpParameterBinding for more general scenarios. Is it okay to read the request body in a ModelBinder ASP.NET 5, or is there a better mechanism for that? If so, then case closed and I will port my ModelBinder with a few minor changes.
I'm not sure that IInputFormatter will work for me in this case either.
Here are two rough approaches
Approach 1:
A quick and dirty approach would be to start with a Dto model
public class Dto
{
public Serializable Result { get; set; }
public Serializable FromForm
{
get { return Result; }
set { Result = value; }
}
[FromBody]
public Serializable FromBody
{
get { return Result; }
set { Result = value; }
}
}
public class Serializable
{
}
And an action method
public IActionResult DoSomething(Dto dto)
{
// Do something with Dto.Result
}
Then write a custom model binder for Serializable, that just works with Request.Form this way you never actually read the body yourself, and Form only reads it if it of type Form.
The down side of this is that ApiExplorer will not provide correct details (but I think since this is none-standard you are going to be in trouble here anyways).
Approach 2
You can alternatively just use the code from BodyModelBinder and create a custom binder for Serializable type above, that first tries to get it from the Form, and if it fails tries to get it from the Body. The Dto class in that case is not necessary.
Here is some pseudo code
if (inputType is yourtype)
{
if (request.Form["yourkey"] != null)
{
Use Json.Net to deserialize your object type
}
else
{
fall back to BodyModelBinder code
}
}
With this approach you can make it generic, and ApiExplorer will say the way to bind the type is unknown/custom (we haven't decided on the term yet :) )
Note:
Instead of registering the model binder you can use the [ModelBinder(typeof(customBinder))] attribute to apply it sparingly.
Here is a link to the BodyModelBinder code.
There is a new [FromHeader] attribute that allows you to bind directly to http header values if that is what you need.
https://github.com/aspnet/Mvc/issues/1671
https://github.com/aspnet/Mvc/search?utf8=%E2%9C%93&q=fromheader

How to validate a single field in a Spring bean?

It seems like the preferred way to validate a spring annotated bean is by using #valid, like in the block below, however I want to display error messages one field at a time still using Spring annotations. I know I can validate the whole form after each field and show only messages for a single field, but that is inefficient, anyone know of a better way?
#RequestMapping(value="/register",method=RequestMethod.POST)
public #ResponseBody RegisterResponse registerSubmit(#Valid #ModelAttribute("registerData") Register registerData, BindingResult result ){
RegisterResponse rr= new RegisterResponse();
if(!result.hasErrors()) {
rr.setStatus("SUCCESS");
rr.setResult(result);
}
else {
rr.setStatus("FAIL");
rr.setResult(result.getAllErrors());
}
return rr;
}
Return from the Validator#validate method upon hitting the first Error.
For this
You need to have a Custom Validator implementing org.springframework.validation.Validator where you have control of validating the fields in the order you need, whereas, using #Valid annotation will validate all the fields in your Form Bean and return the BindingResult for all the fields.
I was able to make things work by filtering out the errors that had an empty/null fields, this does work but is a bit inefficient since we validate entire bean even though we care for the first field. I'd love to hear of a better way to accomplish this kind of step by step form field validation.
I used something like the following:
private List<ObjectError> removeEmpties(BindingResult result) {
List<ObjectError> errors = result.getAllErrors();
ArrayList<ObjectError> myErrors = new ArrayList<ObjectError>();
for(ObjectError error: errors){
FieldError realThing = (FieldError) error;
if (realThing.getRejectedValue()!=null && !realThing.getRejectedValue().toString().isEmpty()){
myErrors.add(error);
}
}
return myErrors;
}

The difference between object validation and persistence validation in DDD?

Right now, I have a domain entity named StyleBundle. This StyleBundle takes a list of Styles:
public class StyleBundle
{
public StyleBundle(List<Style> styles)
{
this.Styles = styles;
}
public IEnumerable<Style> Styles { get; private set;}
}
So, in my original design, a StyleBundle should never be created with an empty Style list. This was a rule that the domain experts basically said was good.
I wrote this using a guard clause in the constructor:
if (styles.Count() == 0)
throw new Exception("You must have at least one Style in a StyleBundle.");
which made sure I could not create StyleBundle in an invalid state. I thought an exception made sense here b/c a StyleBundle being created without at least one Style was exceptional in the system.
Of course, change came down the road during the rest of the project, and now it should be possible for a user to create a StyleBundle without Styles, but they should not be allowed to PERSIST a StyleBundle without Styles.
So now I'm looking at my guard clause and realizing that I can't have the exception thrown from the constructor anymore.
Moving forward, I have a Service/Application layer that my code-behinds interact with when they're working with StyleBundles. In my Service Layer, I have a StyleBundleService class, and that class exposes basic functionality to the UI... among them is "CreateStyleBundle".
It seems as if I'll have to have my Service Layer check to see if the StyleBundle does or does not have any Styles before it's persisted to the database, but something about this decision feels "wrong" to me.
Anyone run into a similar thing? Basically, the different between the state of an object being valid when "new'ed up" vs. the state of the same object when it comes to persistence?
Thanks!
Mike
I would add an IsValid method to your entity. This would check if the entity is currently in a valid state (in your case, check if there are styles).
This method can be called from your Repository to check if an entity may be persisted. You can add more rules to the IsValid method for specific entities and you can implement something like a collection of Validation errors is you want to throw a meaningful exception.
Expanding what Wouter said, plus handy BeforeSaving and BeforeDeleting methods:
public interface IDomainObject<T>
{
bool IsValid();
}
public interface IEntity<T> : IDomainObject<T>
{
}
public interface IAggregateRoot<T> : IEntity<T>
{
void BeforeSaving();
void BeforeDeleting();
}
public interface IAggregateRoot { //or simply IEntity depending on the model
bool IsValid();
}
public class StyleBundle : IAggregateRoot<T> {
return styles.Count() > 0
}
public class StyleBundleRepository : Repository<StyleBundle> {
}
public abstract class Repository<T> : IRepository<T> where T : class, IAggregateRoot<T> {
public T Save(T t)
{
t.BeforeSaving(); //for all AggregateRoots, maybe logging what the aggregate was like before the changes
if(!t.IsValid())
throw Exeception("Entity invalid");
EntityStore.Current.SaveChanges();
// "AfterSaving" here, i.e.: log how the entity looks after the update
}
}
Edit: I dont personally use the IsValid idea, I go with a full class of EntityValidationErrors where I can report back to the client what was wrong before attempting to save, things that shouldnt be null, shouldnt be empty (like your Styles etc)
There are multiple strategies:
Some developers prefer to create 2 methods in the entity itself, one called IsValid() which validates the entity in terms of business rules (general validation) and another one called IsValidForPersistence() which validates the entity for persistence.
Regarding IsValid() I prefer instead not to allow invalid state in the first place by validating all inputs, and to support invariants I use factory or builder.
you may check the link http://www.codethinked.com/thoughts-on-domain-validation-part-1
for some thoughts.
I know, this question is three years old, but seeing the current answer is something I like to respond to. We are talking about the domain data. Hence, there can't be a valid StyleBundle with 0 objects. I imagine, you have a frontend editor somewhere, were you create a "new" StyleBundle and have to add at least one style, before hitting the "save" button.
At this point in the frontend, you won't have a domain object. You may have a data transfer object, that will be send with a "CreateNewStyleBundle" command.
In my opinion, the domain object must be agnostic to persitance and should always be in a valid state. If you have to call a "IsValid" method, you circumvent the whole idea of having domain objects in the first place.
That's just my humble opinion.

How do you handle data validation in the model using ColdFusion Model-Glue?

MVC best practices state that the model should handle input/data validation. Let's say that we have a model that creates new user accounts, with the following fields and constraints:
Username - not null, not already in DB
Password - not null, alphanumeric only
E-mail - not null, not already in DB, valid e-mail format
We have an AccountModel with a CreateNewUser() function:
component
{
public void function CreateNewUser(string username, string password, string email)
{
// create account
}
}
Then we have a controller that processes a form post and tells the model to create the account:
component
{
public void function NewUser()
{
var username = event.getValue("username");
var password = event.getValue("password");
var email = event.getValue("email");
var accountModel = new AccountModel();
accountModel.CreateNewUser(username, password, email);
event.addResult("UserCreated");
}
Now I want to add validation. If the user fails to provide input for all three fields, the application should show the user three validation error messages. This is easy enough to do in the controller:
// assumes that ValidateInput() is a function on the controller that returns an array
var validationErrors = ValidateInput(username, password, email);
// if there were any validation errors, return a ValidationError result
if (len(validationErrors)
{
event.setValue("validationerrors", validationErrors);
event.addResult("ValidationError");
}
else
{
event.addResult("UserCreated");
}
And the view will pull the validationerrors variable and display the error messages.
However, this logic is supposed to reside in the model. How do I do this? I can think of two ways:
Method 1: Move ValidateInput() from the controller to the model. Now the controller has to call ValidateInput() first before CreateNewUser(). If the programmer forgets to do this, CreateNewUser() will throw a validation exception. The downside to this is that now every data operation that requires validation will need an if/else block.
Method 2: Forego having to call ValidateInput() and just call CreateNewUser() directly. If there were any validation errors, an exception will be thrown and it will contain the error message array. This method would work in C#, but it looks like ColdFusion does not support returning of data with the exception, only an exception message and type. Also, every data operation will require a try/catch block.
Method 3: ??
How would you handle validation in this case? Is method 1 what most people do when it comes to validation in the model? Or do people typically use method 2? Or is there a method 3 that I'm not thinking of?
I don't think you should couple the validation of the user's data entry to the creation of the user's account: they are too different things.
If you couple the two together, it means you're basically doing form validation every time you create an account, which doesn't seem right to me.
I see form validation as a UI concern, more than a concern of the objects that might be ultimately created from that data. Obviously your createNewUser() method has its own business rules (which will probably closely mirror that of the validation for a create-new-user form, but they are still separate concerns).
It is possibly a bit unorthodox, but I will put a validateUserData() (or something) method in my User CFC which the form-validation model then calls to help with the validation. This means the business rules for a user are in the same place, and can be called separately. Thereafter, createNewUser() works on a garbage-in/garbage-out principle.
Sidenote: createNewUser() is a bit of a tautological name, innit? What other sort of user would you be creating other than a new one? Also, if it's in your Account.cfc; is it a new user or a new account that's being created? If an account and a user are not synonymous and an account might exist without a user (or vice-versa), perhaps you ought to have a User.cfc too. Then again, this code you've given us could simply be for the purposes of illustration, and you've got all this covered.

Entity Objects Validation and Business Rules Validation

I am developing application having business objects created from EF 4.0. The application is layered with Data Layer having repository of classes. Above that is a business layer where business processes are mapped as per the requirements. Business layer is calling data layer.
Business objects have complex associations. One scenario:
Merchant has Multiple Addresses
Merchant belongs to one Category
Merchant has an Account
Account has a Wallet
User will be creating a new merchant along with above mentioned business objects (graph). There are various business rules when creating and updating a merchant.
I would like to split my validations into two sub sections. 1) Scalar Property Validation to be handled by Validation Blocks 5.0 and 2) Business Process Rules Validation to be handled in business layer components. However, i am facing difficulty on having a centralized way to report broken rules (Scalar Properties validation and Business Process Rule Validation). I don't want to inject exceptions everywhere where business rule in is violated as per the business process mapped.
One e.g is following:
When creating a new merchant, Category needs to be validated. Because if a certain type category is associated with this new merchant then business rule says that such merchant cannot exists twice in the system.
Now, when a UI pass the new merchant graph to business layer component, i first validate BO Scalar properties validation (validated bu Validation Blocks) then this BO is passed into business process rule validation methods to check various rules. There are possible violation points which i want to report and shall not allow the merchant and graph objects to be persisted.
Please share any value able design approach to manage centralized validation rule logging and reporting to UI layer.
EDIT: I don't want to incorporate validations on EF SaveChanges, ChangeAssociation etc event handlers.
While you said you don't want to throw exceptions, I found throwing exceptions very effective. Especially when you having multiple sub systems validating the system, throwing one single type of exception as a facade will be very effective.
What you can do is creating a custom exception (i.e. named ValidationException) that will be thrown either when your Validation Application Block (VAB) reports error or the business rules report errors. In the presentation layer you will have to catch this ValidationException and report this exact type of exception in a user friendly way to the end user.
Using a single exception type for both validation sub systems, allows you to report errors in a consistent way, and also ensures that validation errors won't get unnoticed when you (or an other developer) forgets to handle validation errors. Handling errors should be very explicit IMO. When you let methods return a list of errors it is easy to forget to handle them. When creating a custom exception, it is easy to add a property to that exception type that contains a list of validation errors. Such a list of errors is easily extracted from VAB. I don't know what validation system you use for your business rules validation, but it can't be to hard to extract a list of error codes from it.
The most simple way to handle this in UI is of course by using a try-catch:
var businessCommand = new CreateNewMerchantCommand();
businessCommand.Name = "Wikki";
// etc
try
{
businessCommand.Execute();
}
catch (ValidationException ex)
{
UIValidationHelper.ReportValidationErrors(ex.Errors);
}
Of course having these try-catch statements all over the place is ugly, but at least this code is easy to follow. Dependent on how you structured your business layer and the UI technology you use, there are prettier solutions you could use. For instance, you can wrap the actual operation that can fail with an action as follows:
var businessCommand = new CreateNewMerchantCommand();
businessCommand.Name = "Wikki";
// etc
UIValidationHelper.ExecuteOrDisplayErrors(() =>
{
businessCommand.Execute();
});
The UIValidationHelper would look like this:
public static class UIValidationHelper
{
public static void ExecuteOrDisplayErrors (Action action)
{
try
{
action();
}
catch (ValidationException ex)
{
// Show the errors in your UI technology
ShowErrorMessage(ex.Errors);
}
}
}
An other option, that I've used myself in the past, is by extending the business layer with events. For this to work you need a construct such as commands, as I use in my examples. When using events, the UI could look like this:
var businessCommand = new CreateNewMerchantCommand();
businessCommand.Name = "Wikki";
// etc
businessCommand.ValidationErrorOccurred +=
UIValidationHelper.DisplayValidationErrors;
businessCommand.Execute();
This example hooks a static method to the ValidationErrorOccurred event of a command instance. The trick here is to let the Execute method of that command catch ValidationExceptions and route them to the ValidationErrorOccurred when it is registered. When no method is registered, this exception should bubble up the call stack, because an unhandled validation exception should of course not get unnoticed.
While it is possible to of course do this directly from your business layer, it would make your business layer dependent on a particular validation technology. Besides this, this method allows clients to choose to handle validation errors in any way they want or decide not to handle them at all (for instance when you don’t expect any validation errors to occur in a particular use case).
When using ASP.NET Web Forms, the DisplayValidationErrors method of the UIValidationHelper could look like this:
public static class UIValidationHelper
{
public static void DisplayValidationErrors(
object sender, ValidationErrorEventArgs e)
{
Page page = GetValidPageFromCurrentHttpContext();
var summary = GetValidationSummaryFromPage()
foreach (var result in e.Error.Results)
{
summary.Controls.Add(new CustomValidator
{
ErrorMessage = result.Message,
IsValid = false
});
}
}
private static Page GetValidPageFromCurrentHttpContext()
{
return (Page)HttpContext.Current.CurrentHandler;
}
private ValidationSummary GetValidationSummaryFromPage(Page page)
{
return page.Controls.OfType<ValidationSummary>().First();
}
}
This static helper method injects the messages of the reported errors into a ValidationSummary control on the page. It expects the page to contain a ValidationSummary control at root level of the page. A more flexible solution can easily be created.
The last thing that I like to show you is how the the BusinessCommand would look like when adopting this solution. The base class of these commands could look something like this:
public abstract class BusinessCommand
{
public event EventHandler<ValidationErrorEventArgs>
ValidationErrorOccurred;
public void Execute()
{
try
{
this.ExecuteInternal();
}
catch (ValidationException ex)
{
if (this.ValidationErrorOccurred != null)
{
var e = new ValidationErrorEventArgs(ex);
this.ValidationErrorOccurred(this, e);
}
else
{
// Not rethrowing here would be a bad thing!
throw;
}
}
}
protected abstract void ExecuteInternal();
}
The ValidationErrorEventArgs looks like this:
public class ValidationErrorEventArgs : EventArgs
{
public ValidationErrorEventArgs(ValidationException error)
{
this.Error = error;
}
public ValidationException Error { get; private set; }
}
I hope this all makes sense and sorry for my long answer :-)
Good luck.
Object member validation can be done within encapsulated business objects. Whether you do this in the setter properties or as separate method calls is up to you. Should the objects be set with values that are invalid, should the application allow data into the system that is of the wrong type, range checks etc.
As for the Rules part, I would look at the visitor pattern for each object graph that your trying to achieve some rules checking on. I would report this back probably as a new nested object based on what was found. My personal preference to this reporting side, is to use a visitor pattern that produces an XML Document or some other custom nested class depending on your efficiency needs. The actual rules within the visitor pattern can be declared outside of the visitor pattern, preferably in a declarative approach. For example CheckDuplicateRecord. This would allow for reuse.
Keep all this in the same layer as the Business Layer, but further sub divide the business layer into a Rules validation layer and the Business Objects.
My personal approach with using EF is to use POCO objects as these allow for scalability. I would then do some validation on the UI, then do some validation when transported to the Business Object layer, then do the same again in the EF DAL layer.

Resources