In Spring MVC, is there a way to implement error levels? - spring-mvc

Within Spring MVC, is there way to identify the 'level' or 'type' of error? Examples include information, warning, and error messages?
Btw, this is purely for formatting purposes. For example, error messages tend to be in red text while warning messages are simply black.
** Updating for clarity:
In our current system, we have multiple levels of messages: error, warning, info. Is there anything built into SpringMVC, that allows me to set an error message's level?
Also, it appears that we're using BindingResults in the Controllers (specifically BeanPropertyBindingResults), and triggering a Validator (our custom class that implements Spring's Validator interface).
During validation we end up writing something like:
ValidationUtils.rejectIfEmptyOrWhitespace(errors, modelVariable, "required", new Object[] {variableDisplayName});
Or
errors.rejectValue("field", "fieldName");

In the end, we ended up extending ObjectError and FieldError to include a new field, 'ErrorLevel'. When creating a new error -we use these new objects so that we can set the ErrorLevel. On the JSP, we look for the ErrorLevel to determine how to display the messages.

First of all, there's no such thing as 'level' or type of error in existing validation features.
But if you want to achieve level of error just like logging error levels, you can do so by setting the errors as list in request flashmap.
Eg.
RequestContextUtils.getOutputFlashMap(request).put("ERROR_MESSAGES", Arrays.asList("test error"));
RequestContextUtils.getOutputFlashMap(request).put("WARN_MESSAGES", Arrays.asList("test error"));

Related

EntityMetadataWrapperException: Invalid data value given

On editing a node with a user of a particular role i get the following error a Drupal site. With only user 1 it works. Can't figure why. I debug the entity file, but it seems that the id disappear after iteration.
EntityMetadataWrapperException : Invalid data value given. Be sure it matches the required data type and format. dans EntityDrupalWrapper->set() (ligne 737 dans /sites/all/modules/entity/includes/entity.wrapper.inc).
No coding yet has been done for this only using contrib modules.
Since you haven't done any coding, it's probably bug of some contrib module, Entity API or you're dealing with malformed entity.
Try applying this patch: Add field information to exception message on validation exception, this will allow you to see on which value it fails.
In case you're using some custom coding, then check Entity metadata wrappers page for some examples. The common mistake is to not use array() for set() when dealing with multi-valued field, or opposite - extra array for single-valued field.
If you can reproduce the problem, you can debug the issue either by step-by-step debugger and do the breakpoint on Exception line, or do it manually by temporary adding: var_dump(debug_backtrace()); exit; just before the exception happens, so PHP can dump the backtrace of your current code with all the argument passed, so you can track your malformed entity or identify the failing contrib module.
See also: How to set a value on a field collection using entity metadata wrapper at DA

Model Binding and Validation Errors

I am using asp.net MVC3 and I am very new to this technology.
My models are designed in such a way that the properties will throw validation errors if the data is invalid. In this case, the properties are not set with invalid data.
When I redisplay my editing-view, validation error messages are shown; however the values that the user previously entered are gone because the model that it is bound to only contains the old-valid data.
For example, say I had a Person class and the Name property cannot be a null or empty string otherwise it throws a validation exception and prevents the property from being set. Now say the user removes the value from the Name property and tries to save the Person from the web. A validation exception will be thrown and handled properly to add the error to the ModelState so that it is displayed on the screen; however the old value for the Name is redisplayed since the invalid, empty string never made it into the property.
I do not know how to solve this problem and any advice on the issue would be greatly appreciated.
My advise is allow invalid data but use validation attributes. You wont save invalid entities so there is no problem and this is the standard approach these days. If you don't want do that, there is no easy solution. Most simple solution would be using the info from Request.Form
You should implement IValidatableObject to performe this kind of validation at server side.
From MSDN IValidatableObject Interface:
Provides a way for an object to be invalidated.
Theres an exemple here Using IValidatableObject Custom Validation, also from MSDN.
The solution to this problem was to create a ViewModel that allowed invalid data to be entered into this. This solution also simplified my ModelBinder classes because it took on most of the work.

How can I display the invalid value that caused a Type Mismatch during Model Binding?

We're using strongly typed model and form objects in Spring 3.1 MVC, this works well and allows us to manage our with a low overhead of code. However our users like the invalid values to remain in the field when an invalid value is displayed, particularly so users don't have to retype long amounts that were off by one typo. This works fine for validation errors, but presents a problem for binding errors, as the value will not fit in the model. I know I can get the invalid value from the FieldError, but how can I get it back to the view (JSP)?
You have access to the BindingResult in the JSP. You could simply get the field errors directly. It would look something like this:
<forEach items="${requestScope['org.springframework.validation.BindingResult.formBean'].getFieldErrors('fieldName')}" var="fieldError">
<!-- do something with the FieldError -->
</forEach>
In this case, the form bean/model attribute/command object is called "formBean", and the field is called "fieldName". Once you have fieldError, you can do what you want with it.

ASP.NET - displaying business layer errors in the presentation layer

Currently in the ASP.NET application I'm developing, basic validations (ie required fields) are being done in the Presentation Layer, using Validators and a ValidationSummary. This is working great for me specifically since the ValidationSummary will display multiple error messages (assuming multiple Validators are set to invalid).
I also have some validations being done in the business layer - due to their complexity (and data service layer reliance) I'd rather not keep them in the presentation layer. However, I'm not sure the best way to send these back to the presentation layer for display to the user. My initial consideration is to send back a List<string> with failed validation messages and then dynamically create a CustomValidator control (since apparently you can only bind one error message to one Validator control) for each error to show in the ValidationSummary when there are any.
I'm assuming I'm not the first one to come across this issue, so I'm wondering if anyone has any suggestions on this.
Thanks!
There are essentially two ways to do this: either by passing back an error code/object from your business layer, or throw out an exception. You can also combine both.
For an example, you can take a look SqlException class. When you send a SQL to SQL Server, it runs a query parser to parse your SQL first. If it sees syntax error, then it will throw out a SqlException and terminate the query. There may be multiple syntax errors in your query. So SqlExeption class has an Errors property that contains a list of errors. You can then enumerate through that list in your presentation layer to format your error message, probably with a CustomValidator.
You can also simply just return the error list without throwing an exception. For example, you can have your function to return a List in case at least one error occurred and return null in case the call was successful. Or you can pass List as an argument into your function. They are all fine, it all depends on which way you feel is more convenient. The advantage of throwing out an exception is it unwinds multiple call frames immediately, so you don’t have to check return value on every level. For example, if function A calls function B , B calls function C, C sees something wrong, then if let C to return an error object (or error code), then B has to have code to check whether C returned an error and pass that error code/value back, A have to check it as well ---- you need to check it on every level. On the other hand, if you just let C to throw an exception, then the code goes straight to the exception handler. You don’t have check return values on every level.

Which exception to throw when not finding a WebForms control which "should" be there

We have a WebForms Control which requires that the ID of another Control implementing ITextControl is provided.
What exception should we throw if there is no control with that ID or a control is found but it's not implementing the interface?
var text = Page.FindControl(TextProviderId) as ITextControl;
if (text == null) {
throw new WhatEverException(...);
...
Should we split it into two cases and throw one exception if there is no control with that ID, and another one if said control does not implement ITextControl? If so, which exceptions should we use then?
If the control should really be there, I would say that your web form is in an invalid state if it is missing, so I would probably go for InvalidOperationException:
The exception that is thrown when a method call is invalid for the object's current state.
This would be applicable to both scenarios; regardless of whether the control is missing or if it does not implement the expected interface, the containing object is in an invalid state.
If this is a scenario that is expected to happen for various reasons (let's say that you are making some tool that others will program against, and this is a situation that they might very well produce), perhaps you should instead create two custom exceptions that make it very clear what is happening and how to correct it (such as ControlNotFoundException and InterfaceNotFoundException or something similar).
ArgumentOutOfRangeException?
Whether or not you should split them up into different exceptions probably depends most on whether or not you think it is likely that anyone will ever want to distinguish the two exceptions in different catch blocks.
Not knowing exactly how this will be used, this seems like the kind of error that should be brought to the developer's attention, where rewriting code to point to the correct file or implement the correct interface is the proper action, rather than implementing a try-catch and give the user friendly error messages. As such, I'd just throw an ArgumentException.

Resources