spring 3 propertyeditor throws exception - spring

New Problem:
I register / bind my custom property editor and get an java.lang.IllegalArgumentException - as expected.
The problem: I do not know how to create a custom error message if binding fails.
Any idea?
THX!
#InitBinder( { "playerCreationBean" } )
protected void initBinder( final WebDataBinder binder )
{
binder.registerCustomEditor(Date.class, new DatePropertyEditor());
}

axtavt is right. If you have a message bundle in your application (ie, messages.properties in your classpath, being used by a MessageSource implementation) spring can automatically use the friendly message in the bundle. The message 'typeMismatch' is just one of a number of default messages that are used by the binding framework, depending on the name of the object being bound as well as the property being bound to. You can use a debugger to inspect the errors instances after binding and find which messages are created by default when a binding exception occurs. I've found that the Spring Documentation is a bit lacking when it comes to the default message names that are generated.

Related

Classcastexception for CloudEventMessageConverter to AbstractMessageConverter

when using spring cloud stream latest version with cloud events spring sdk
Facing classcastexception in below scenario.
Message has contentType = application/*+avro.
SmartcompositeMessageConverter contains converter list like below -
CloudEventMessageConverter
AvroSchemaRegisteryClientMessageConverter
and some ootb converters.
While converting to message from producer..
SmartcompositeMessageConverter has this line of code for wildcard contentType
((AbstractMessageConverter) converter).getSupportedMimeTypes()
But CloudEventMessageConverter is not an instance of AbstractMessageConverter, hence it throws an exception.
Please guide what should be overridden in this case.
If I create a new CloudEventMessageConverter which extends AbstractMessageConverter, I cann't add headers as only method allowed to override is convertFromInternal which returns just the payload.

Global Exception Handling via Spring Advice In a MQ based Spring Boot Application

I've a MQ Spring Boot PaaS application where I need to implement exception handling via a common exception handler class (GlobalExceptionHandler). My PaaS application receives message from a source queue, perform some database operations via spring jpa and write the response back to a destination queue.
I need to handle all the database RuntimeException, custom business exceptions and other checked exceptions via GlobalExceptionHandler class.
My GlobalExceptionHandler will have handlers (method) defined for every exception. In my handler, I will be logging the exception first and then I will be creating a [error code, desc] and then I need to return it back to main flow.
I do not have any controller in my application. So I think, I can't use #ControllerAdvice. Currently I'm using spring AOP #AfterThrowing as below but I'm not able to return the [code, desc] from handlers.
#AfterThrowing(pointcut = "execution(* com.abc.xyz.service..*(..)) ",
throwing = "dataNotFoundException")
public void handleDataNotFoundException(DataNotFoundException dataNotFoundException) {
LOGGER.info("Info : " + dataNotFoundException.getMessage());
// code, desc need to create here and send it back to calling place.
// I need to change the return type here from void.
}
Can anyone please guide me in implementing exception handling here.
As I explained here, #AfterThrowing cannot modify return values or otherwise change the execution flow of your epplication. You cannot even catch the exception there. You need to use an #Around advice instead.
I suggest you read some documentation first and then ask more follow-up questions.

Customize spring boot validation message from database

I am using spring validation to validate the Rest Controller input, I would appreciate if any one can tell me is there a possibility of throwing custom message in case of exception and the custom message should come from database rather than from a properties file.
You can achieve this by setting a custom validation message source on Spring's LocalValidatorFactoryBean.
Your message source needs to implement the MessageSource interface and read its messages from the database.
Reference:
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/validation/beanvalidation/LocalValidatorFactoryBean.html#setValidationMessageSource-org.springframework.context.MessageSource-
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/MessageSource.html

How to get Spring mvc validation messages without using messages.properties?

I have a Spring mvc application with a Controller, Model, Service, and Validation classes. Everything works fine. In developing what I currently have, I stored the validation messages in a messages.properties file -which I registered in a configuration class like this:
#Bean
public MessageSource messageSource() {
final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("[package name]/messages/messages");
return messageSource;
}
In the Validator, I add a validation message if the user didn't answer a field such as this:
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "age", "required", new Object[] {"Age"});
In the messages.properties file I have this (above 'age' is the name of the model object, 'required' is the key used to retrieve the message in the messages.properties file):
required = {0} is required.
Ok, again -this all works fine. But what I'd like to do is externalize the messages to a database (basically, these are corporate messages that all applications use).
My question is -how do I get Spring to use the database instead of messages.properties? Or is I do use messages.properties, to only store the message's id (database key) instead of the message itself?
I have a couple ideas of what to do -but no idea how to do either one. I 'think' that the Spring-form tag library ends up performing the work of getting the actual message. Perhaps I could somehow intercept that call? Or maybe somehow change the messageSource to something else rather than defining the messages.properties file.
Anyways, does anyone have any ideas?
You can try Errors.rejectValue(String field, String errorCode, String defaultMessage) method. I too had the same problem. In my case I used ...errors.rejectValue("firstName", "error.firstName", "plz enter ur first name!!.");
This should ideally use the defaultMessage in the scenario where it can't find the error code from message source.
Instead of using a ResourceBundleMessageSource use a custom MessageSource implementation, which back in a DB. Unfortunately Spring itself doesn't have such an implementation, as described in the jira issue: https://jira.springsource.org/browse/SPR-364
But implementing the MessageSource Interface is straightforward, you can even see a sample implementation attached to the jira issue: https://jira.springsource.org/secure/attachment/10261/JdbcMessageSource.java

How to configure spring HandlerExceptionResolver to handle NullPointerException thrown in jsp?

From a jsp is thrown a NullPointerException for example using <% null.toString(); %>
This exception is not handled by the HandlerExceptionResolver, but thrown to the web container(tomcat) and converted into a code 500 error.
How can I configure spring to get that error in my HandlerExceptionResolver ?
Details:
Spring can be configured to handle exceptions thrown inside Controllers, but not exceptions thrown by view.
Of course i can resolve the NullPointerException, but i want to design a solution that will gracefully resolve any possible problem on the web application in order to display a user friendly message to the user.
See the HandlerInterceptor interface instead. You'll want the afterCompletion method. You can then intercept the response and then set the appropriate header information to redirect to a container-configured error web page. You're right that Spring doesn't have this functionality, this is going to have to be specified by the web.xml which determines which codes map to which pages.
I have not worked with this particular bit of the spring framework, but the docs say
"Interface to be implemented by objects than can resolve exceptions thrown during handler mapping or execution, in the typical case to error views. Implementors are typically registered as beans in the application context.
Error views are analogous to the error page JSPs, but can be used with any kind of exception including any checked exception, with potentially fine-granular mappings for specific handlers."
so I'd imagine that given that NullPointer extends RuntimeException the framework isn't designed to catch it. Is there a reason the exception(s) can't be handled in the controller directly?

Resources