Spring MVC: bind an exception handler to particular method - java

Good day!
I have a #Controller. Some of its methods throw the same exception, but I want to handle this exceptions in different way.
Is there a way how to bind an #ExceptionHandler to a particular method?

You need to use AOP tools like CDI Interceptor or AspectJ to achieve this cross-cutting concerns. A Concern is a term that refers to a part of the system divided on the basis of the functionality.
Basically this type of feature is used to handle logging, security and also handling the errors... which are not part of your business logic...
Like if you want to change the logger for application from log4j to sl4j then you need to go through each and every classes where you have used log4j and change it. But if you have used AOP tools then you only need to go the interceptor class and change the implementation. Something like plug and play and very powerful tool.
Here is a code snippet using JavaEE CDI Interceptor
/*
Creating the interceptor binding
*/
#InterceptorBinding
#Retention(RUNTIME)
#Target({TYPE, METHOD})
public #interface BindException {
}
After we have define interceptor binding we need to define interceptor binding implementation
/*
Creating the interceptor implementation
*/
#Interceptor
#BindException
public class ExceptionCDIInterceptor {
#AroundInvoke
public Object methodInterceptor(InvocationContext ctx) throws Exception {
System.out.println("Invoked method " + ctx.getMethod().getName());
try {
return ctx.proceed(); // this line will try to execute your method
// and if the method throw the exception it will be caught
} catch (Exception ex) {
// here you can check for your expected exception
// code for Exception handler
}
}
}
Now we only need to apply interceptor to our method
/*
Some Service class where you want to implement the interceptor
*/
#ApplicationScoped
public class Service {
// adding annotation to thisMethodIsBound method to intercept
#BindException
public String thisMethodIsBound(String uid) {
// codes....
// if this block throw some exception then it will be handled by try catch block
// from ExceptionCDIInterceptor
}
}
You can achieve same feature using AspectJ also.
/*
Creating the Aspect implementation
*/
#Aspect
public class ExceptionAspectInterceptor {
#Around("execution(* com.package.name.SomeService.thisMethodIsBound.*(..))")
public Object methodInterceptor(ProceedingJoinPoint ctx) throws Throwable {
System.out.println("Invoked method " + ctx.getSignature().getName());
try {
return ctx.proceed(); // this line will try to execute your method
// and if the method throw the exception it will be caught
} catch (Exception ex) {
// here you can check for your expected exception
// codes for Exception handler
}
}
}
Now we only need to enable the AspectJ to our application config
/*
Enable the AspectJ in your application
*/
#Configuration
#EnableAspectJAutoProxy
public class AppConfig {
#Bean
public SomeService SomeService() {
return new SomeService();
}
}
/*
Some Service class where you want to implement the Aspect
*/
package com.package.name;
public class SomeService {
public String thisMethodIsBound(String uid) {
// codes....
// if this block throw some exception then it will be handled by try catch block
// from ExceptionAspectInterceptor
}
}
I have code example in my git repo https://github.com/prameshbhattarai/javaee-exceptionBinding by using CDI interceptor.

Just as an option (obviously, it's not ideal): you can wrap the exception into a custom exception in one of your methods and then catch it in an #ExceptionHandler
void boo() throws WrappingException {
try {
} catch (TargetException e) {
throw new WrappingException(e);
}
}
then
#ExceptionHandler(WrappingException.class)
public void handleWrappingException() {
// handle
}
#ExceptionHandler(TargetException.class)
public void handleTargetException() {
// handle
}

Could you please explain why do you need this? I'm asking out of curiosity, because I've never felt like this is required and here is why:
Exception usually represents a very specific "mistake" - something that went wrong in a very specific way.
Basically, exception represents a mistake, not a flow...
There are two "degrees of freedom" that spring can support out of the box:
Exception parameters. Maybe stuff like error code, which can be declared as a data field of exception itself.
Exception inheritance. Example:
If you have in your system a UserDoesNotExistException and you want to be more specific in a case of say, the system that manages the users that are retired in some flows, you can always create a more specific exception:
class UserRetiredException extends UserDoesNotExistException {...}
Obviously, spring can support both the cases: In ExceptionMapper you have the access to the exception anyway so you can do something like:
handleException(SomeExceptionWithErrorCode ex) {
if(ex.getErrorCode() == "A") {
// do this
}
else if(ex.getErrroCode() == "B") {
// do that
}
}
In the second case you just have different exception mappers for the different types of exceptions.
You can also consider #ControllerAdvice annotation to reuse code or something.

I don't think you can specify a specific #ExceptionHandler for a method, but you can bind an #ExceptionHandler method to a specific Exception.
So if you want to handle all DataIntegrityViolationException one way and all other Exceptions in another you should be able to achieve that with something like this:
#ExceptionHandler(DataIntegrityViolationException.class)
public void handleIntegrityViolation() {
// do stuff for integrity violation here
}
#ExceptionHandler(Exception.class)
public void handleEverythingElse() {
// do stuff for everything else here
}

You can derive sub-exceptions from the common exception thrown by other methods according to how you want to handle them.
Say you have declared the parent exception as ParentException. Derive sub classes like ChildAException extends ParentException, ChildBException extends ParentException etc.
Define a #ControllerAdvice class that catches the ParentException and define the specific behaviors in delegate methods.
#ControllerAdvice
public class ParentExceptionHandler {
#ExceptionHandler(ParentException.class)
public ResponseEntity<Object> handleParentException(ParentException pe) {
if (pe instanceof ChildAException) {
return handleChildAException((ChildAException) pe);
} else if (...) {
...
} else {
// handle parent exception
}
}
private ResponseEntity<Object> handleChildAException(ChildAException cae) {
// handle child A exception
}
}

I just got the same issue like you. So I checked the spring source code for this situation. It seems that spring will search in the #Controller class for any method that is annotated with #ExceptionHandler first, if nothing matched then it will continue to search for all class that is annotated with #ControllerAdvice. So you can just use the strategy below:
MyController with a #ExceptionHandler method:
#RestController
public class MyController {
#RequestMapping("/foo")
public String foo() {
throw new IllegalArgumentException();
}
#ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handle(IllegalArgumentException ex) {
return new ResponseEntity<>("Specific handler", HttpStatus.BAD_REQUEST);
}
}
AnotherController without any method annotated with #ExceptionHandler:
#RestController
public class AnotherController {
#RequestMapping("/bar")
public String bar() {
throw new IllegalArgumentException();
}
}
A global #ControllerAdvice class:
#ControllerAdvice
public class GlobalExceptionHandler {
#ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handle(IllegalArgumentException ex) {
return new ResponseEntity<>("Global handler", HttpStatus.BAD_REQUEST);
}
}
Then if you visiting http://ip:port/foo, you will get 400 status code with Specific handler, and 400 status code with Global handler when you visit http://ip:port/bar.

I agree that the inability to map a specific #ExceptionHandler to handle only one specific method in the #RestController should be a very desirable feature.

I tried try{}catch(Exception ex){} and catch no exception. But
exception handler handles it nicely.
Since we are talking about hibernate exceptions, these exceptions are usually thrown at the commit phase of transaction. The problem here is that seems like you have transaction opened right in your controller which is considered as a bad practice.
What you should do is - open transaction in the application layer.
Controller just maps xml/json to incomming RequestDto object.
And then you call the Service to handle the business logic.
The Service(or its method) should be annotated by #Transactional.
#RestController
public class MyController {
#Autowired // but better to use constructor injection
private MyService myService;
public ResponseDto doSomething(RequestDto request) {
try {
myService.doSomething(request);
} catch (DataIntegrityViolationException ex) {
// process exception
}
}
}
#Transactional
class MyService {
public void doSomething() {
// do your processing which uses jpa/hibernate under the hood
}
}
Once you done that, the try catch will start behaving as expected on controller level.
However, I would even go further as DatabaseExeption shouldn't really go that far to controller. The alternative would be to use manual transaction inside of a service and do a try catch there.
Then in the Service layer transform database exception in a more generic exception with all necessary information for controllers to process.
And then you should catch that more generic exception (MyDatabaseAccessException) in the controller and transform as you wish for the sake of a presentation layer.
===
The #ControllerAdvice suggested here is good for a global exception handling across controllers.
The #ExceptionHandler is not suitable for each method unless you wnat to have controller per method. And even after that it can clash with global #ControllerAdvice.
I am not sure why spring doesn't allow #ExceptionHandler at a method level, it would simplify a lot of cases like yours.

My solution is to annotate a method with a marker:
#ExceptionHandler(SomeException.class)
public ResponseEntity<String> handleSomeException(SomeException e, HandlerMethod handlerMethod) {
var marker = AnnotatedElementUtils.findMergedAnnotation(handlerMethod.getMethod(), MarkerAnnotation.class);
if (marker != null) return something();
else return somethingElse();
}

Related

How to handle Exception in controller for Spring Boot REST API?

I am confused of how I should handler the exception of the controller in a Spring Boot Rest API. Right now I throw some exception in my service classes like this:
public Optional<Item> getSpecificItem(Long itemId) throws Exception {
return Optional.ofNullable(itemRepository.findById(itemId).
orElseThrow(() -> new Exception("Item with that id doesn't exist")));
}
I don't know if this is the correct way to do it but it kind of works, I am open to criticism. For the controller classes I don't know how it should look, I saw some example with #ControllerAdvice and exception for each controller and that looked kind of bad to me. Can I have a global exception class for all controllers? Is it good practice ?
Saw some examples and I don't know if they were the correct way to do it.
#ControllerAdvice is good if you not use for general Exception. Example, if you define spec exception such as SkyIsRedException. So, it will be throw anywhere it will catch.
#ControllerAdvice
public class ExampleAdvice {
#ExceptionHandler(SkyIsRedException.class)
#ResponseCode(HttpStatus.NOT_FOUND) // <- not required
public void methodName1() { ... }
#ExceptionHandler(SkyIsGreenException.class)
public void methodName2() { ... }
}
And you can this #ExceptionHandler in controller too, so it will activate if any methods of controller will throw this SkyIsRedException.
I not recommend use Exception for everything. You are only harming yourself.
UPDATE:
// annotations
public class Controller {
// annotations
public Optional<Item> getSpecificItem(Long itemId) throws ItemNotExistException {
return Optional.ofNullable(itemRepository.findById(itemId).
orElseThrow(() -> new ItemNotExistException("Item with that id doesn't exist")));
}
// Controller specific exception handler, not central like #ControllerAdvice
#ExceptionHandler(ItemNotExistException.class)
#ResponseStatus(HttpStatus.NOT_FOUND)
public String itemNotExistExceptionHandler(ItemNotExistException ex) {
return ex.getMessage(); // example
{
}

Java/Springboot: Catch and handle a particular exception in one place?

Is it possible to catch all thrown exceptions of a particular type, say IllegalArgumentException, throughout the entire Spring Boot application and handle it one place? I want to introduce some additional logging for particular types of exception in application and I am looking for a way to avoid duplicating logic or method calls throughout the application?
Take a look at the annotation #ExceptionHandler(value=YourException.class) and #ControllerAdvice it allows you to handle custom exceptions. The Controller Advice class can handle the exception globally. We can define any Exception Handler methods in this class file.
#ControllerAdvice
public class ProductExceptionController {
#ExceptionHandler(value = ProductNotfoundException.class)
public ResponseEntity<Object> exception(ProductNotfoundException exception) {
return new ResponseEntity<>("Product not found", HttpStatus.NOT_FOUND);
}
}
Spring AOP can be used to address this cross cutting concern.
#AfterThrowing advice can be used for this purpose.
The name used in the throwing attribute must correspond to the name of
a parameter in the advice method. When a method execution exits by
throwing an exception, the exception is passed to the advice method as
the corresponding argument value. A throwing clause also restricts
matching to only those method executions that throw an exception of
the specified type
Example can be found here
Springboot provides us with the capability to handle exceptions globally using the #ControllerAdvice annotation . So, instead of handling exceptions and logging it in each controller, you could actually throw the exception from every controller and handle it in a single place like :
BusinessException extends RunTimeException {
public BusinessException(String message, Throwable cause) {
super(message, cause);
}
}
#ControllerAdvice
public class ExceptionController {
#ExceptionHandler(value
= { BusinessException.class,IllegalArgumentException.class})
protected ResponseEntity<Object> handleCustomException(
RuntimeException ex, WebRequest request) {
String bodyOfResponse = "This should be application specific";
return handleExceptionInternal(ex, bodyOfResponse,
new HttpHeaders(), HttpStatus.NOTFOUND, request);
}
}
In your case, you could create a custom exception class and throw your custom exception from where ever your custom logic is needed. So, your could then handle this custom exception globally to provide your logic. This is one way to handle exceptions globally without duplicating logic. You could also do this using spring aop using pointcut.
#Aspect
public class LoggingAspect {
#AfterThrowing (pointcut = "execution(* com.yourservice.yourpackage.*(..))", throwing = "ex")
public void logAfterThrowingAllMethods(Exception ex) throws Throwable
{
System.out.println("****LoggingAspect.logAfterThrowingAllMethods() " + ex);
}
}
Just add spring aop and aspectJ as dependencies for this approach.

Spring-Retry cannot locate recovery method when implement an interface

I found a problem when doing spring-retry with spring boot. When a class implements an interface, it cannot enter the #recover method after exceeding the maximum number of retries. But when I inject a normal class, I can enter this method.Your prompt help and kind advices would be much appreciated,thanks!
When I do this,I can enter the #Recover method
#Service
public class TestService {
#Retryable(Exception.class)
public String retry(String c) throws Exception{
throw new Exception();
}
#Recover
public String recover(Exception e,String c) throws Exception{
System.out.println("got error");
return null;
}
}
But once the class implement another interface, it's not works
#Service
public class TestService implements TestServiceI{
#Override
#Retryable(Exception.class)
public String retry(String c) throws Exception{
throw new Exception();
}
#Recover
public String recover(Exception e,String c) throws Exception{
System.out.println("got error");
return null;
}
}
Spring-Retry uses AOP to implement the #Retry. When using AOP the default is to use JDK Dynamic Proxies. JDK Dynamic Proxies are interface based.
This means you get a dynamically created class that pretents to be a TestServiceI however it isn't a TestService. The proxy doesn't include the recover method (as it isn't on the interface) and as such Spring Retry cannot detect it.
To fix you need to enable class based proxies for Spring Retry by setting the proxyTargetClass attribute on #EnableRetry to true (see the javadoc).
#EnableRetry(proxyTargetClass=true)
mark proxyTargetClass=true: #EnableRetry(proxyTargetClass = true)
The #Recover method must return the same type as the original method;

Rollback Annotation in Java

I have service calls in my application that make remote network calls to other services as well as DB calls. Spring Boot has good support for rolling back bad transactions with #Transactional, but I wanted to know if I could define a custom rollback procedure using an annotation.
I would need to rollback the data on the other services as well as the database.
In code, I could do it like this:
#Transactional
public void doSomethingComplicated() {
try {
srvcOne.makeRemoteNetworkCall();
srvcTwo.makeDatabaseCall();
} catch(Exception e) {
srvcOne.rollBackNetworkCall();
}
}
but I was hoping I could do something like this:
#Transactional
#MyCustomRollbackListener(handler = MyCustomRollBackHandler.class)
public void doSomethingComplicated() {
srvcOne.makeRemoteNetworkCall();
srvcTwo.makeDatabaseCall();
}
and in the handler:
public class MyCustomRollBackHandler {
public void handleRollback() {
srvcOne.rollBackNetworkCall();
}
}
I implemented a global exception listener and I am able to get the class the exception came from, but I have no way to get the method and to retrieve any annotations on it. Here is my initial attempt:
#ControllerAdvice
public class RollbackExceptionListener{
private static final Logger logger = LoggerFactory.getLogger(RollbackExceptionListener.class);
#ExceptionHandler(Exception.class)
public void lookForAnnotationClassForException(final Exception exception) {
logger.error("Exception thrown", exception);
final StackTraceElement topElement = exception.getStackTrace()[0];
final Class callingClass = topElement.getClass();
final String methodName = topElement.getMethodName();
try {
// Can't get the method with just the name, need to
// know the params as well.
final Method method = callingClass.getMethod(methodName);
// Retrieve the annotation on the method and call the handler
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
Is there anyway to do something like this?
Arguments are not part of the Stacktrace. If the method is unique, i.e. not overloaded, you can probably find it with getMethods()? Something else that comes to mind, maybe you can look at Aspects to wrap the method in some handler before it is executed. Can be done either at compile time or runtime.
The aspect can do the rollback itself, it can enrich the exception with the information you need, or it can set some ThreadLocal variable with the handler class that was defined in the method before re-throwing the exception. You can then get this value from the ThreadLocal at the point where you catch the exception.

Where can I catch non rest controller exceptions in spring?

I have the spring mvc application. To catch exceptions I use #ExceptionHandler annotation.
#ControllerAdvise
public class ExceptionHandlerController {
#ExceptionHandler(CustomGenericException.class)
public ModelAndView handleCustomException(CustomGenericException ex) {
....
}
}
But I think that I will catch only exceptions after controller methods invocations.
But how to catch exceptions generated outside the rest context? For example lifecycle callbacks or scheduled tasks.
But how to catch exceptions generated outside the rest context? For
example lifecycle callbacks or scheduled tasks
One solution that I can think of it, is to use a After Throwing Advice. The basic idea is to define an advice that would caught exceptions thrown by some beans and handle them appropriately.
For example, you could define a custom annotation like:
#Target({ElementType.METHOD})
#Retention(RetentionPolicy.RUNTIME)
public #interface Handled {}
And use that annotation to mark methods that should be advised. Then you can annotate your, say, jobs with this annotation:
#Component
public class SomeJob {
#Handled
#Scheduled(fixedRate = 5000)
public void doSomething() {
if (Math.random() < 0.5)
throw new RuntimeException();
System.out.println("I escaped!");
}
}
And finally define an advice that handles exceptions thrown by methods annotated with #Handled:
#Aspect
#Component
public class ExceptionHandlerAspect {
#Pointcut("#annotation(com.so.Handled)")
public void handledMethods() {}
#AfterThrowing(pointcut = "handledMethods()", throwing = "ex")
public void handleTheException(Exception ex) {
// Do something useful
ex.printStackTrace();
}
}
For more finer grain control over method executions, you could use Around Advice, too. Also don't forget to enable autoproxy-ing, using #EnableAspectJAutoProxy on a Java config or <aop:aspectj-autoproxy/> in XML configurations.

Categories

Resources