Spring JMS MessageListenerAdapter handleListenerException - spring

The default implementation of onMessage in AbstractAdaptableMessageListener does simply:
onMessage(Message message) {
try {
onMessage(message, null);
} catch(Throwable ex) {
handleListenerException(ex);
}
}
Even though the attempt at handling exception is commendable the actual handling in handleListenerException is not sufficient in most cases (it just logs an error level message about the exception). Most real application who would love to make use of the MessageListenerAdapter and simply create a POJO to receive the formatted message have much more granular exception handling requirements.
Why was it done like this and could the onMessage implementation simply be replaced with a call to the onMessage method with a null Session argument and no try catch and simply allow the application to intercept (Java Enterprise interceptor or Spring Aspect) the onMessage JMS method and perform integrated/coherent exception handling? In the past, I have had to subclass MessageListenerAdapter simply to override either the onMessage or handleListenerException method to handle exceptions myself.

Related

Handling validation error of a JSON payload in Spring RabbitListener

Let's take the following consumer method for a RabbitMQ queue. Ths payload received from the queue is in JSON format, so I register a bean returning a Jackson2JsonMessageConverter. This basically works fine.
Now I'd like to add a validation of the QueueResponse object, similar to when using Jackson in a #RestController, e.g. if the JSON field does not exist or contains an invalid value. In this case, I'd like the code to execute the catch block, i.e. throwing an AmqpRejectAndDontRequeueException.
Thus, I added #Payload #Valid as described in the documentation. But I don't know what to do in the validationErrorHandler method. I don't understand the return statement from the documentation. What would I need to do there to reach the catch block?
#RabbitListener(queues = QUEUE_NAME, messageConverter = "jackson2MessageConverter", errorHandler="validationErrorHandler")
public void consume(#Payload #Valid QueueResponse queueResponse) {
try {
processMessage(queueResponse);
} catch (Exception e) {
throw new AmqpRejectAndDontRequeueException(e.getMessage());
}
}
#Bean
public MessageConverter jackson2MessageConverter() {
return new Jackson2JsonMessageConverter(objectMapper);
}
// Not sure what to do here...
#Bean
public RabbitListenerErrorHandler validationErrorHandler() {
return (m, e) -> {
...
};
}
If the error handler exits normally, the message will be acknowledged (discarded).
If the error handler throws an exception, the message will either be requeued (and redelivered) or discarded (and optionally sent to a dead letter queue), depending on the exception type, container properties, and queue arguments.
Basically what I do in the RabbitListenerErrorHandler is the following:
check how many times I requeued a message by looking into the count property in the x-death header
then decide to either requeue the message by throwing an AmqpRejectAndDontRequeueException or not. In this last case, instead of just discard the message, send it to a parking-lot exchange (bound to a queue with no consumer, in my case these queues are monitored externally) with additional information (for instance the stack trace of the last failure)

How Runtime Exceptions are handled by Spring ExceptionHandler

I am using spring's #ControllerAdvice and #ExceptionHandler for exception handling.
Any method throws custom exception from Controller and corresponding #ExceptionHandler handle it. If Runtime exception occurs(eg any HibernateException) then it will throw Runtime Exception and I dont have any #ExceptionHandler for RuntimeExceptions.
My question is how to handle any runtime exception? do I need to add #ExceptionHandler for every Exception that is thrown by controller?
I dont want create an Generic ExceptionHandler for Exception.class because I have to send different error code according to exception occured.
one way to do it add try catch block in Controller and then throw the custom exception from catch block?
or is there any another better way?
All #ExceptionHandlers are inside #ControllerAdvice class.
the alternative is don't catch Exception in Controller. catch all Exception in service layer and throw a custom Exception eg. if you persisting a record failed, throw DatabaseException with message. see below method:
Student persist(Student object){
try{
studentDao.insert(object);
}catch(HibernateException e){
throw new DatabaseException("database operation failed!");
}
return student;
}
from you exception handler method you can get the message. this way you can set different message on different Exception.

spring transaction at service layer

In our application we are applying spring declarative transactions using annotations at service layer.
Here i am not getting any idea on how to handle exceptions properly.
What exactly my requirement is when dao layer throws any hibernate exception we are rolling back the transaction, but in one case i am getting InvalidDataAccessResourceUsageException because there is a unique index violation happening. So what i would like to do here is i want to catch InvalidDataAccessResourceUsageException exception at service class and have to rethrow the application specific exception to controller.
But whats happening here is as we have transaction demarcation at service layer class the session is flushing at service layer(ie when tx commits) after executing the method, as a result i cant catch it into the same method and it is directly propagating to the controller.
Please suggest me work around on this.
also seeking one more clarification, suppose i have a method like below
#Transactional(value="transactionManager",readOnly = false, propagation = Propagation.REQUIRED,rollbackFor = HibernateException.class)
public SomeDTO editObject(SomeDTO someDto, String user) throws EditException {
try{
/*
call to dao.edit();
another call to anotherDao.addEditsTOAnotherTable();
some business logic*/
} catch(HibernateException e){
} catch(InvalidDataAccessResourceUsageException ie){}
}
Can i catch exceptions as above. Note: I am not handling or throwing any exceptions from dao. Also there is no session cache mechanisms like FlushMode.ALWAYS etc at dao layer as it will flush during tx.commit().
By default #Transactional will rollback for any RuntimeException, and since HibernateException is a RuntimeException , roll back will be done automaticaly and you don't have to add rollbackFor = HibernateException.class
You can handle Exception this way:
try{
}catch(InvalidDataAccessResourceUsageException e){
throw new YourApplicationExceptionNotUniqueIndex();
}
and :
YourApplicationExceptionNotUniqueIndex shoud extends RuntimeException that way you wil have a rollback at your sevice layer and you can catch the exception at your Controller .
Better to handle check all the database constraints before editing into database

How to handle session expired exception in Spring MVC-Spring Security app for GWT RPC calls

I have Spring MVC application where security is handled by Spring Security.
UI is built using GWT which gets the data from server using RPC approach.
I need to handle on UI the situation when session is expired:
For example RPC AsyncCallback can get SessionExpiredException type of exception and popup the window with message like "You session is expired, please click the refresh link" or something.
Did someone deal with such problem?
Thanks.
I suppose that for processing of incoming GWT call you use some Spring MVC controller or some servlet. It can have following logic
try{
// decode payload from GWT call
com.google.gwt.user.server.rpc.RPC.decodeRequest(...)
// get spring bean responsible for actual business logic
Object bean = applicationContext.getBean(beanName);
// execute business logic and encode response
return RPC.invokeAndEncodeResponse(bean, ….)
} catch (com.google.gwt.user.server.rpc.UnexpectedException ex) {
// send unexpected exception to client
return RPC.encodeResponseForFailure(..., new MyCustomUnexpectedException(), …) ;
}
Solution for this case
HttpServletRequest request = getRequest() ;
if (request.getRequestedSessionId() != null && !request.isRequestedSessionIdValid()) {
return RPC.encodeResponseForFailure(..., new MyCustomSessionExpiredException(), …) ;
} else {
// first code snippet goes here
}
Then catch custom session expired exception in a client side code. If you do not use RPC directly then provide more details about your bridge implementation between GWT and Spring.
You will need also force GWT compiler to include MyCustomSessionExpiredException type to a serialization white list (to prevent case when GWT security policy stops propogation of the exception to client side). Solution: include MyCustomSessionExpiredException type to each method signature of each synchronous interface:
#RemoteServiceRelativePath("productRpcService.rpc")
public interface ProductRpcService extends RemoteService {
List<Product> getAllProducts() throws ApplicationException;
void removeProduct(Product product) throws ApplicationException;
}
MyCustomSessionExpiredException extends ApplicationException
Then show pop-up in client side code:
public class ApplicationUncaughtExceptionHandler implements GWT.UncaughtExceptionHandler {
#Override
public void onUncaughtException(Throwable caught) {
if (caught instanceof MyCustomSessionExpiredException) {
Window.alert("Session expired");
}
}
}
// Inside of EntryPoint.onModuleLoad method
GWT.setUncaughtExceptionHandler(new ApplicationUncaughtExceptionHandler());
I researched a bit and uploaded the solution here http://code.google.com/p/gspring/source/browse/#svn%2Ftrunk%2Fsample%2Fsession-expired%253Fstate%253Dclosed.
Use mvn jetty:run-war to see the demo after checking it out and go to rpc-security-sample/index.htm
There are two ways to solve it.
The first is around to pass the delegate proxy for GWT RemoteServlet which throws SessionExpiredException during method invocation. This requires to declare Exception in every RPC service method. Example: http://code.google.com/p/gspring/source/browse/#svn%2Ftrunk%2Fsample%2Fsession-expired%253Fstate%253Dclosed
Steps:
Develop new filter which intercepts first
Declare SessionExpiredException in each RPC method service which could inherit RuntimeException for simplicity (no need to follow this in implementers)
Develop parent generic AsyncCallback handler
Use http://code.google.com/p/gspring/ solution to handle all incoming RCP requests.
The second which is much more simplest: return the 401 HTTP error and handle in UI side (GWT native general exception contains the HTTP status number). Example: http://code.google.com/p/gspring/source/browse/#svn%2Ftrunk%2Fsample%2Fsession-expired-401
The second approach is simplest and does not require declaring Exception in service methods contract. However following the first approach can give you some flexibility: it could contain some additional info like last login time (for SessionExpiredException) etc. Also the second approach can introduce new exceptions which are inherited from SecurityException like blacklisted user (for example if user was blacklisted during his session) or for example if user does the same actions very often like a robot (it could be asked for passing the captcha) etc.

Linking Server Side Message/Exception with AJAX request

I am making an ajax submit using Primefaces but I am having trouble linking my server side message with my ajax request.
Supposed I have this button that calls an action.
In my managed bean, do I need to raise an exception? How do I pass this message into my ajax request
public void checkout(ActionEvent event){
if(expression){
throw new CustomException("Account balance is not enough!");
}
}
public class CustomException extends RuntimeException {
public CustomException(String message) {
super(message);
}
}
How do I handle this case? Will my onerror javascript method be able to handle this?
Also, in one case supposed DB is down then how do I handle the exception? Do I have accessed to the error message
in my javascript function?
public void checkout(ActionEvent event){
try{
//DB is down
if(expression){
throw new CustomException("Account balance is not enough!");
}
}catch(Exception e){
}
}
As to your concrete question, you need to implement a custom ExceptionHandler for this which does basically the following when an exception occurs in an ajax request:
String errorPageLocation = "/WEB-INF/errorpages/500.xhtml";
context.setViewRoot(context.getApplication().getViewHandler().createView(context, errorPageLocation));
context.getPartialViewContext().setRenderAll(true);
context.renderResponse();
This is not exactly trivial if you want to take web.xml error pages into account. You'd need to parse the entire web.xml for this to find the error page locations. The OmniFaces utility library has exactly such an exception handler, the FullAjaxExceptionHandler. You can find the full source code here and the showcase example here.
As to your concrete functional requirement, I wouldn't throw an exception when there's just an user error. This is fully recoverable. You need to create and add a FacesMessage and have ajax to update the <h:messages>, <p:messages> or <p:growl>. The PrimeFaces ones support an autoUpdate="true" which would auto-update itself on ajax requests. E.g.
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Insufficient balance", null));
with
<p:messages autoUpdate="true" />
Throwing an exception makes only sense in unrecoverable situations like as when the DB is down. Note that you usually don't throw such an exception yourself. In case of JPA it would already be thrown as PersistenceException which you in turn shouldn't catch in JSF managed bean, but just let it go.

Resources