Spring 3 controller exception handler implementation problems - java

I was hoping to implement a single "ExceptionController" to handle exceptions that are thrown in execution of my other controllers' methods. I hadn't specified any HandlerExceptionResolver in my application context so according to the API documentation the AnnotationMethodHandlerExceptionResolver should be started. I verified it as such in the source. So why doesn't the following work?
#Controller
public class ExceptionController {
#ExceptionHandler(NullPointerException.class)
public ModelAndView handleNullPointerException(NullPointerException ex) {
// Do some stuff
log.error(logging stuff)
return myModelAndView;
}
}
#Controller
public class AnotherController {
#RequestMapping(value="/nullpointerpath")
public String throwNullPointer() {
throw new NullPointerException();
}
}
I see in the debug logs that the three default exception handlers are asked for handling of the exception, but nothing is done and I see "DispatcherServlet - Could not complete request". Followed by the user being displayed the stacktrace and a 500 Internal error.

Make sure your Exception handler is returning a view that exists/maps to a handler.

You should write your exceptionhandler to the same class with which you want to handle, like the following.
#Controller
public class AnotherController {
#ExceptionHandler(NullPointerException.class)
public ModelAndView handleNullPointerException(NullPointerException ex) {
// Do some stuff.
log.error(logging stuff)
return myModelAndView;
}
#RequestMapping(value="/nullpointerpath")
public String throwNullPointer() {
throw new NullPointerException();
}
}

I don't think this is a good design. Controllers in Spring handle HTTP requests and map to URLs. I don't think "exception" fits into either bin. It feels like a misuse of Spring to me.
An exception is not an HTTP request. You don't map an exception to a URL. Therefore I'd conclude that controllers aren't intended to be treated as exception handlers.
Controllers are a part of the Spring API, but your design isn't using them as intended, so that's why it's not working. Re-think your design.

Related

#ExceptionHandler for Error gets called only if there's no mapping for Exception

Using spring-web-4.2.6, I have the following Controller and ExceptionHandler:
#ControllerAdvice
public class ExceptionsHandler {
#ExceptionHandler(Exception.class)
public ResponseEntity<ErrorDTO> HandleDefaultException(Exception ex) {
...
}
#ExceptionHandler(InternalError.class)
public ResponseEntity<ErrorDTO> HandleInternalError(InternalError ex) {
...
}
}
#RestController
#RequestMapping("/myController")
public class MyController {
#RequestMapping(value = "/myAction", method = RequestMethod.POST)
public boolean myAction() {
throw new InternalError("");
}
}
For some reason, the ExceptionsHandler's HandleDefaultException (for Exception.class) method is invoked, with an exception of type NestedServletException, instead of the HandleInternalError call.
When removing the default call, the IntenalError call is called with the proper InternalError exception.
I do not want to remove the default call as it is important to me to have a default handler to allow for a better experience for my users.
What am I missing here?
EDIT:
Apparently I'm using spring-web-4.3.3, without asking for it. I don't understand why exactly, here's my Gradle dependencies tree: http://pastebin.com/h6KXSyp2
Spring MVC should only exhibit the behavior you describe with version 4.3 and above. See this JIRA issue. Previously, Spring MVC would not expose any Throwable values to #ExceptionHandler methods. See
ExceptionHandler doesn't work with Throwable
Since 4.3, Spring MVC will catch any Throwable thrown from your handler methods and wrap it in a NestedServletException, which it will then expose to the normal ExceptionHandlerExceptionResolver process.
Here's a short description of how it works:
Checks if the handler method's #Controller class contains any #ExceptionHandler methods.
If it does, tries to resolve one that can handle the Exception type (including NestedServletException). If it can, it uses that (there's some sorting if multiple matches are found). If it can't, and the Exception has a cause, it unwraps and tries again to find a handler for that. That cause might now be a Throwable (or any of its subtypes).
If it doesn't. It gets all the #ControllerAdvice classes and tries to find a handler for the Exception type (including NestedServletException) in those. If it can, it uses that. If it can't, and the Exception has a cause, it unwraps it and tries again with that Throwable type.
In your example, your MyController throws an InternalError. Since this is not a subclass of Exception, Spring MVC wraps it in an NestedServletException.
MyController doesn't have any #ExceptionHandler methods, so Spring MVC skips it. You have a #ControllerAdvice annotated class, ExceptionsHandler, so Spring MVC checks that. The #ExceptionHandler annotated HandleDefaultException method can handle Exception, so Spring MVC chooses it to handle the NestedServletException.
If you remove that HandleDefaultException, Spring MVC won't find something that can handle Exception. It will then attempt to unwrap the NestedServletException and check for its cause. It'll then find the HandleInternalError which can handle that InternalError.
This is not an easy issue to deal with. Here are some options:
Create an #ExceptionHandler that handles NestedServletException and do the check for InternalError yourself.
#ExceptionHandler(NestedServletException.class)
public ResponseEntity<String> HandleNested(NestedServletException ex) {
Throwable cause = ex.getCause();
if (cause instanceof InternalError) {
// deal with it
} else if (cause instanceof OtherError) {
// deal in some other way
}
}
This is fine unless there's a bunch of different Error or Throwable types you want to handle. (Note that you can rethrow these if you can't or don't know how to handle them. Spring MVC will default to some other behavior, likely returning a 500 error code.)
Alternatively, you can take advantage of the fact that Spring MVC first checks the #Controller (or #RestController) class for #ExceptionHandler methods first. Just move the #ExceptionHandler method for InternalError into the controller.
#RestController
#RequestMapping("/myController")
public class MyController {
#RequestMapping(value = "/myAction", method = RequestMethod.POST)
public boolean myAction() {
throw new InternalError("");
}
#ExceptionHandler(value = InternalError.class)
public ResponseEntity<String> HandleInternalError(InternalError ex) {
...
}
}
Now Spring will first attempt to find a handler for NestedServletException in MyController. It won't find any so it will unwrap NestedServletException and get an InternalError. It will try to find a handler for InternalError and find HandleInternalError.
This has the disadvantage that if multiple controllers' handler methods throw InternalError, you have to add an #ExceptionHandler to each. This might also be an advantage. Your handling logic will be closer to the thing that throws the error.

Custom Annotation Spring MVC ResultBinding

I have a simple MVC controller that I annotate with my custom annotation:
#PreAuthorize("hasRole('GESTION_BENEFICIAIRE')")
#AuthentificationForte(otp = "#{args[0]}",transactionId="#{args[1]}")
#RequestMapping(value = "/ajouter", method = { RequestMethod.POST, RequestMethod.GET })
public String addBeneficiaire(#ModelAttribute("beneficiaireForm") BeneficiaireForm beneficiaireForm,
BindingResult result, Model model, Principal principal) {
[...]
}
My custom annotation is linked with an aspect that throws a RuntimeException when the validation doesn't succeed.
#Around(value = "#annotation(annotation)")
public Object verifyOtp(final ProceedingJoinPoint jointPoint,
final AuthentificationForte annotation) throws Throwable {
try {
if (authentificationForteEnabled) {
[...]
} else {
throw new AuthentificationForteException();
}
} else {
return jointPoint.proceed();
}
} finally {
}
}
So now the behavior is that when the validation fails, I am redirected to a 500 Error page. My goal is to stay in the same page and add a rejected message to the BindingResult:
result.rejectValue("suiteRib", "BeneficiaireForm.InvalidRib");
I haven't found a way to do that, the only way that I've found is to change all my logic and not use the annotation, while using a validation service with a try/catch in the controller code.
Is there any way to handle this and to access the binding result and add the error message when the aspect throws this exception?
Most definitely.
There is an example here of manipulating args:
Aspectj overwrite an argument of a method
You can also autowire services into the aspect class (remember to mark it #Configurable).
If you know the arguments before hand, then I think they can be included into the point cut definition, in which case they can be referred to directly in the around method. This is much nicer was as the arguments come strongly type.
You can read more here: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html
May be its too late to answer your question but there are two ways you can handle it :
Have a try catch around proceed() in your aspect and when you get runtime exception you can either return the response from the aspect ( like a generic JSP showing the cause of error or generic JSON with error message.)
Second option could be to use Spring Exception Handler Controller advice. Spring MVC provides nice exception handler controller mechanism to call specific handler method for given type of exception class. ( Here is the blog link : https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc )
We currently have an application where we use mix of this approach to handle exception.

What are some options for java messaging from service layer to front end

So in my Service layer I have some logic that does some stuff. Sometimes it has to check to see if something is possible before it does it OR it just has to get some OK from the front end ("Are you sure you want to do this?" kind of stuff). The front end, of course, sends a transaction to the screen to get the info.
In the past I have used RuntimeExceptions for this. I will throw a
new MessageException("are.you.sure");
and then the controller level will do a
try{
theService.doSomething();
}catch(MessageException me) {
model.addAttribute(me.getMessageKey());
result.addError(new ObjectError());
}
In another application I made a PostOffice object and would put letters and such in it for messages. It was quite elaborate and very nice, but my new app is much smaller and I don't want all that.
So I am looking for some best practices. How do you guys send messages from the service layer to the front end? And keep in mind, I am NOT talking about Exceptions! I am just talking about messages from the service layer.
One beautiful thing about Spring MVC is the Exception handling. Since the DispatcherServlet has a try-catch(Exception) wrapping the handler method (ie. your controller method), it can catch all exceptions thrown and handle them with #ExceptionHandler methods or some other construct (there are alternatives).
What I've started doing is making my Service methods only throw RuntimeException instances (works well with #Transactional) and define all my #ExceptionHandler methods in a #ControllerAdvice annotated class. Something like:
#ControllerAdvice
public class ControllerHandler {
private static final Logger logger = LoggerFactory.getLogger(ControllerHandler.class);
#ExceptionHandler(value = AuthenticationException.class)
public String handleAuthenticationException(AuthenticationException e) {
if (logger.isInfoEnabled()) {
logger.info("An AuthenticationException occurred: {}", e.getMessage());
}
return "redirect:/";
}
...more
}
#ExceptionHandler annotated methods have a few rules, but are very customizable. You can see all possibilities in the javadoc here. You should also take a look at ResponseStatus.
Personally, I rarely throw checked exceptions from my service layer. The only one that often appears is IOException (parsing JSON, opening files) and even that I like to wrap in a RuntimeException, because it's not like I can do anything special about it at that level.

#ExceptionHandler not firing

This has been asked a few times in Google-land, but I can't seem to apply those resolutions to my situation. My J2EE application uses Spring and I was previously using SimpleMappingExceptionResolver to intercept Exceptions to show a friendly error page for my users. One of the guys on my team has his own package and is using an extended Exception class as a vehicle to communicate validation errors to his users. So now every time a user enters invalid data, it triggers an exception page. He refuses to change his code (even though I thing he should), so now I am forced to make error handling a package- or controller-specific thing.
I've tried to leverage the #ExceptionHandler annotation to do this, but it doesn't seem to be firing. What am I doing wrong? I am expecting a call to dmapproval to essentially return the applicationError view.
Here is my controller:
#Controller
public class ExecutiveApprovalController {
/*omitted stuff*/
#ExceptionHandler(Exception.class)
public String routToErrorHandler(Exception anExc) {
return "applicationError";
}
#RequestMapping(value = "/dmapproval", method = RequestMethod.GET)
public String dmApproval(Model model, HttpServletRequest request) throws Exception {
throw new RuntimeException(); // just for testing exception logic
}
/*omitted stuff here, too*/
}
Thanks for your help!!
Your snippet looks fine; the only difference between your code and something that I have working is that I annotate the exception handler method like this:
#ExceptionHandler(Throwable.class)
As an aside; this is far less elegant than using SimpleMappingExceptionResolver (which it sounds like you already know!). I'd ask you rogue team-mate to reconsider his validation approach and use Exceptions only in exceptional circumstances ;)
Did you add this config in your servlet-context.xml
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver">

Ensure that web service handles exceptions and always returns a valid response

I am developing a web service, no matter what, the response should always be valid, and I mean valid as in a valid format.
That means that if the web service is expected to return an XML matching a particular XSD schema, it should ALWAYS return a valid XML document, no matter what.
The only approach that I have so far is to do something like this (at controller level)
String xmlResponse = this.loadDefaultXML();
try {
xmlResponse = this.myCoolService.myCoolMethod();
} catch (Throwable t) {
xmlResponse = this.loadDefaultXML(String errorMessage)
} finally {
return xmlResponse
}
Where of course lpoadDefaultXML() will load an xml document like:
<?xml>
<result>Ouch, there was a problem</result>
And loadDefaultXML(String errorMessage) will do
<?xml>
<result>WHATEVER errorMessage contains</result>
Of course the service level takes cares of the normal exceptions, still, I feel that catching Throwable and using the try-catch-finally is the only way to ensure that no matter what, I will be in control so I can return always an XML.
Any better ideas or suggestions?
UPDATE:
I am using Spring MVC 3.2 and JAXB for the marshalling/unmarshalling of xml.
This does use SOAP, also I am not using wsdl for this.
In Spring MVC, when an exception is thrown during the handling of the request, the DispatcherServlet will consult the configured org.springframework.web.servlet.HandlerExceptionResolvers to handle the thrown exception. The resolver can then translate the exception to a view to show the user.
To use it, in short, you can either:
Implement the HandlerExceptionResolver interface, which is only a matter of implementing the resolveException(Exception, Handler) method and returning a ModelAndView.
Or, what I prefer:
You use the #ExceptionHandler method annotation within a controller to specify which method is invoked when an exception of a specific type is thrown during the execution of controller methods. For example:
#Controller
public class PersonController {
#RequestMapping("person/{id}")
#ResponseBody
public Person getById(#PathVariable String id) {
if ("007".equals(id)) {
throw new RuntimeException("007 is a secret agent.");
}
return personService.getById(id);
}
#ExceptionHandler(RuntimeException.class) // this can be an array
#ResponseBody
public String handleRuntimeException(RuntimeException ex,
HttpServletRequest request) {
return "Oops! Something bad happened: "+ex.getMessage();
}
}
Find more info at Web MVC framework - Handling Exceptions.

Categories