Does Spring have any way of catching/handling ServletException? - spring

I there any predefined way in Spring to catch or handle ServletException?
I mean any annotation or class that catches them and provide utility methods for them?

There are several techniques and approaches to handle Servlet Exceptions with Spring.
I can redirect you to this interesting link:
Exception Handling for REST with Spring
Exceptions can be managed at the DispatchServlet level, Controller level or application level. You can chose the method that better fit your needs.
Exception handling can be implemented per controller (using the old #ExceptionHandler or more recent and easy to use ResponseStatusException), or within global exception handler that centralize all exception management (using #ControllerAdvice)

Related

Is there a generic spring-data Exception class to handle exceptions thrown in the repo layer?

I'm using spring-data-jpa to read/write to my DB. I've read through the documentation for spring-data and the one thing that I can't seem to locate is how it handles exceptions.
I am looking to catch any type of exception thrown by a repo action. Is there a way of doing this short of just wrapping the individual repo action in a try/catch and catching any RuntimeException? I'd rather avoid that as that is an even larger catch-all than I'd like.
Does spring-data wrap all exceptions in its own SpringDataException() or something similar? I've looked through the spring-data-commons jar as well as the spring-data-jpa jar and didn't find anything applicable.
Does spring-data wrap all exceptions in its own SpringDataException() or something similar
Yes, sort of. spring-data(-jpa) enable exception translation from JPA exceptions to Spring’s DataAccessException hierarchy:
From spring-data-jpa reference implementation:
...Beyond that, it activates persistence exception translation for all beans annotated with #Repository to let exceptions being thrown by the JPA persistence providers be converted into Spring’s DataAccessException hierarchy.
From Spring reference implementation:
Spring provides a convenient translation from technology-specific exceptions like SQLException to its own exception class hierarchy with the DataAccessException as the root exception. These exceptions wrap the original exception so there is never any risk that one might lose any information as to what might have gone wrong...
For more read about Spring DAO support

What are the other use of Spring AOP except Logging and Exception handling?

Spring AOP and AspectJ are usually used for Exception handling and Logging. Is there any other feature for which we are using aspectJ and spring AOP.
Yes, transactional behavior is the first to come to mind. Take a look at the #Transactional annotation. You mark a method with the annotation and the container will take the necessary steps to start a transaction before your method executes and commit or roll back the transaction when it ends.
Security is another nice application of AOP. You can annotate a method to mark it as requiring certain permissions. For example, in a web application, you might have a few handler methods for requests that require the user to be an administrator. Instead of implementing that logic in each handler method, you extract it to some AOP advice and put a joinpoint at each of those methods.
Aspects can be used as any type of filter really. You can allow, prevent, modify access to a method.
Note that Spring's support for AOP is limited to method invocation join points.

Graceful handling of exception thrown while creating beans

I want my Spring MVC web app to gracefully handle a particular type of exception thrown while creating the beans.
The construction of one of my beans reads configuration data from an external file. If that configuration data is faulty, one of my bean constructors will throw an exception of a particular type. As the cause of the problem would be a faulty configuration file, I want my web application to respond with a useful log message and/or an error page, rather than a stack-trace of the thrown exception. So I guess I need some kind of exception handler hooked into the IOC container or dispatcher servlet. How can I do that?
Just to be clear. I'm asking about exceptions thrown as the servlet is initialising, not as it handles HTTP requests, so #ExceptionHandler annotations on controllers are not useful.
I worked around this difficulty by introducing a level of indirection. My bean is really just a handle. If the configuration file is bad, the bean catches the exception, logs a message, and notes that reading failed. Accessing the bean later then throws a suitable exception.

What is "persistence exception translation" for #Repository beans

I was reading Spring with annotation part and I came across #Repositoryannotation
I read that #Repository beans differ from #Component beans in the sense that they are eligible for persistence exception translation.
Can somebody please elaborate what is meant by persistence exception translation?
Persistence Exception Translation is the process of converting low level persistence exceptions into high level Spring exceptions.
From the SpringSource Site:
Common data access exceptions. Spring can wrap exceptions from your
O/R mapping tool of choice, converting them from proprietary
(potentially checked) exceptions to a common runtime
DataAccessException hierarchy. This allows you to handle most
persistence exceptions, which are non-recoverable, only in the
appropriate layers, without annoying boilerplate catches/throws, and
exception declarations. You can still trap and handle exceptions
anywhere you need to. Remember that JDBC exceptions (including DB
specific dialects) are also converted to the same hierarchy, meaning
that you can perform some operations with JDBC within a consistent
programming model.
One of the major benefits of this is that exceptions are turned into Runtime Exceptions, in effect you are not required to add the throws declaration to your methods signature.
http://static.springsource.org/spring/docs/2.5.x/reference/orm.html
It provides a consistent exception hierarchy regardless of the database type or persistence methodology/technology you're using.
You get the same exceptions for the same types of errors regardless of whether you're using Oracle vs MySQL or JPA vs JDBC.
Take a look at the SQLErrorCodeSQLExceptionTranslator and sql-error-codes.xml.
sql-error-codes.xml is particularly interesting as you can see all the various vendor-specific error codes and what exception in the hierarchy they map to.
The Spring exception translation mechanism can be applied transparently to all beans annotated with #Repository – by defining an exception translation bean post processor bean in the Context

How to add a custom annotation to Spring MVC?

Can anyone explain what I need to do to implement my own annotation that would add functionality to my web requests?
For example:
#Controller
public class MyController {
#RequestMapping("/abc")
#RequiresSomeSpecialHandling
public void handleSecureRequest() {
}
}
Here #RequiresSomeSpecialHandling would be my own annotation that causes some special work to be done before or after the given web request /abc.
I know that on a very high level I would need to write a bean post processor, scan classes for my annotations, and inject custom mvc interceptors when needed. But are there any shortcuts to simplify this task? Especially for the two examples above.
Thanks in advance,
This kind of Annotations, (that add additional functionality when invoking a method) looks like annotations that trigger an AOP Advice.
#see Spring Reference Chapter 7. Aspect Oriented Programming with Spring
The idea is to use the Annotation to trigger the AOP Advice.
like:
#Pointcut("#target(com.example.RequiresAuth)")
Depends on what you want to do as a result of #RequiresSomeSpecialHandling. E.g. do you want it to influence request mappings or the invocation of the method (i.e. resolving method arguments, processing the return value)?
The support for annotated classes in Spring 3.1 became much more customizable. You can browse some examples in this repo.
Also keep in mind that a HandlerInterceptor in Spring 3.1 can cast the handler Object to HandlerMethod, which gives you access to the exact method including its annotations. That may be enough for what you need to do.
If caching is one of your goals, take a look at the #Cacheable annotation (and its siblings #CachePut, #CacheEvict and #Caching), available as of Spring 3.1.

Resources