Error page registrar and Global exception handling - spring-boot

I am creating a Spring Boot web application, but i am confused why people use Global Exception handlers(#ControllerAdvice) when there is Error Page Registrar which is neater and more explicit. Please can someone explain more and is it possible to call an Error page registrar from a global Exception Handler Class( class annoted with #ControllerAdvice, with an #Exceptionhandler method).

As Brian answer, I think you can do this. I got a sample to prove this one in here if you still need to refer: https://github.com/kennytai/SampleSpringbootExceptionHandler
At this sample, I use the #ControllerAdvice in class GlobalExceptionHandler to manage all exceptions from TestController.
Hope this help.

It's actually the opposite the error pages mechanism in Spring Boot is the global one; it's catching all exceptions unhandled by the application. Note that in a Servlet environment, it's even dispatching the request back into the container on the /error path.
You're right though, this mechanism is really powerful and you can achieve a lot with it.
The other exception handling mechanisms you're mentioning are provided by Spring MVC itself. They're executed during the handling of the request and don't require an additional dispatch to the container. In some cases, they can be more limited because they offer less features than the full ErrorController (which is an MVC Controller).
But unlike error pages, you can configure those to focus on only specific errors:
You can declare an #ExceptionHandler within a Controller and specify the type of Exception you'd like to handle
You can configure the #ControllerAdvice annotation to only apply to specific packages, Controllers extending a specific interface or annotated with a specific annotation
I'd say the latter are quite useful when you want to deal with business exceptions at the controller level. You can do that with error pages, but you might end up with a single error controller dealing with too many things.

Related

Handling expected exceptions from dao

I am currently coding a spring-mvc (jsp) project with three layers (controller -> service -> dao) and I am wondering what is the correct way of handling expected exceptions from dao invocations (e.g trying to persist an User that already exists, if it exists then call the register view again with a message saying that the user already exists), at first I thought it would be a good idea to catch the exception in the dao (e.g DataIntegrityViolationException) and throw my arbitrary checked exception so then I can do an exception handler for it in the controller but I fear if I do this then I might have conflicts if I want to make my service methods #Transactional later on since spring won't know how to rollback the transaction.
If this is correct then I have two ideas:
try/catch DataAccessException in the controller when I invoke the service call userService.register(..)
Use something among the lines like userService.findByUsername(username) in the controller (which returns an Optional) and if its present I notify the user before even calling userService.register(..)
Also, our teacher emphasizes on following DDD behavior and trying to avoid leaking business logic in our controllers and I fear both of this solutions do that but I don't really know how to handle it otherwise.
Spring already converts checked JDBC exceptions into more informative unchecked exceptions, which play well with service layer transactions. All your custom checked exceptions do is force you to type more. Spring gives you reasonable defaults, take advantage of them.
Create an exception handler. Spring has multiple ways to implement this, none of them involve writing catch blocks for exceptions in your controller.
Put the business logic in the service, not the controller. It seems like your findByUsername and register can be combined in one transactional service method.

How can I handle Tomcat's MaxUploadSizeExceededException in Spring?

I have done some research around this with conflicting results. To handle this error, some say that I need to implement HandlerExceptionResolver in one of my controllers.
Here are some links for that:
How to handle MaxUploadSizeExceededException
Handling MaxUploadSizeExceededException with Spring MVC
http://www.raistudies.com/spring/spring-mvc/file-upload-spring-mvc-annotation/
On the other hand, other people are saying that this approach is futile such that the Exception is occuring outside the request handling flow:
http://forum.spring.io/forum/spring-projects/web/124409-handling-maxuploadsizeexceededexception-in-spring (The second poster in the thread)
MaxUploadSizeExceededException doesn't invoke the exception handling method in Spring
I have tried the above solutions but they do not work for me. It appears that the Exception occurs outside of Spring, as expected. I am unable to catch this even with HandlerExceptionResolver.
Trying following the approach specified in the link below. Basically, you configure an error page for any un handled exception and then define a handler for the error page. Looks like a decent workaround.
Here is the link http://www.javacodegeeks.com/2013/11/how-to-custom-error-pages-in-tomcat-with-spring-mvc.html
Hope this helps.

Integrate GWT with Spring Security framework

I have searched for tutorials on this topics, but all of them are outdated. Could anyone provide to me any links, or samples about integrating Spring security into GWT?
First of all, you have to bear in mind that GWT application is turned into javascript running on client-side, so there is nothing you can really do about securing some resources out there. All sensitive information should be stored on server side (as in every other case, not only for GWT), so the right way is to think of Spring Security integration from the point of view of application services layer and integrating that security with communication protocol you use - in case of GWT it is request factory in most cases.
The solution is not very simple, but I could not do it in any better way... any refinement suggestions are welcome.
You need to start with creating GWT ServiceLayerDecorator that will connect the world of request factory with world of Spring. Overwrite createServiceInstance method taking name of spring service class to be invoked from ServiceName annotation value and return instance of this service (you need to obtain it from Spring ApplicationContext):
final Class<?> serviceClass = requestContext.getAnnotation(ServiceName.class).value();
return appContext.getBean(serviceClass);
Also, you need to override superclass invoke(Method, Object...) method in order to catch all thrown runtime exceptions.
Caught exception cause should be analyzed, if it's an instance of Spring Security AccessDeniedException. If so, exception cause should be rethrown. In such case, GWT will not serialize exception into string, but rethrow it again, thus, dispatcher servlet can handle it by setting appropriate HTTP response status code. All other types of exceptions will be serialized by GWT into String.
Actually, you could catch only GWT ReportableException, but unfortunately it has package access modifier (heh... GWT is not so easily extensible). Catching all runtime exceptions is much more safe (althouth not very elegant, we have no choice) - if GWT implementation change, this code will still work fine.
Now you need to plug in your decorator. You can do it easily by extending request factory servlet and defining your's servlet constructor as follows:
public MyRequestFactoryServlet() {
this(new DefaultExceptionHandler(), new SpringServiceLayerDecorator());
}
The last thing - you need to do a dirty hack and overwrite request factory servlet doPost method changing the way how it handles exceptions - by default, exception is serialized into string and server sends 500 status code. Not all exceptions should result in 500 s.c - for example security exceptions should result in unauthorized status code. So what you need to do is to overwrite exception handling mechanism in the following way:
catch (RuntimeException e) {
if (e instanceof AccessDeniedException) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
} else {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
LOG.log(Level.SEVERE, "Unexpected error", e);
}
}
Instead of extending classes, you can try to use some 'around' aspects - it is cleaner solution in this case.
That's it! Now you can annotate your application services layer as usual with Spring Security annotations (#Secured and so forth).
I know - it's all complicated, but Google's request factory is hardly extendable. Guys did a great work about communication protocol, but design of this library is just terrible. Of course the client-side code has some limitations (it is compiled to java script), but server-side code could be designed much better...

Unable to call an interceptor before MultipartResolver in Spring

In my spring-3 application I have an AuthenticationInterceptor (which is basically an interceptor) that checks for the privileges for a user. I am using a Spring's MultipartResolver to try an upload a file to the server.
The problem that I now face is that I wish to perform different actions based on user privileges, in case of a MaxUploadSizeExceededException.
However I see that this exception is occurring at the DispatcherServlet level and is caught by HandlerExceptionResolver
I want to be able to call my AuthenticationInterceptor before any of this happens?
Is there a straightforward way.
The problem is that the exception occurs BEFORE the request is dispatched to a controller and because of that, your interceptor also never fires. I guess you have that part figured out already.
Want to get around that...
For starters, I would move the authentication mechanism out IN FRONT of the servlet by using servlet filters. This being said, it makes little or no sense to roll your own solution in that space when a great product like Spring Security can do that for you.
Once you transition to Spring Security (or similar), the user's SecurityContext (roles, permissions, etc.) will have been resolved by the time the exception occurs and is caught.
Now, if I'm reading your question correctly, it seems you might like to respond to the exception differently based on the user's roles, permissions, etc. That should be possible at this point. You'd implement a custom HandlerExceptionResolver that inspects the SecurityContext to see if the user has a certain role or permission and then respond accordingly.
Hope that helps!
There are two basic ways to handle doing something in-stream before the Handler code gets called:
Implement the HandlerInterceptor interface, and code the code you want to run in the preHandle method
Create an Aspect using #Aspect and configure a pointcut to run #Before the method call
In either case, you could check the logged-in user's Roles using SecurityContextHolder.getContext().getAuthentication().getAuthorities() and then decide what to do based on Role membership.

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