scoder
scoder

Reputation: 2611

Better way to handle exception is spring-boot

I have some Ten API which talks to redis for storing the data.

Currently it is throwing nested exception, so I have done like below to handle the nested exception.

    @Override 
    public boolean delMyStatus(String key) {
        try{
            return  redisTemplate.delete(key);
        }
        catch (Exception e){
            if(e.getCause() != null && e.getCause().getCause() instanceof RedisException) {     
                RedisException ex = (RedisException)e.getCause().getCause();
                log.error("RedisException  " + ex.getMessage());
/* Do some action*/
            } else {
                throw new IllegalStateException("...");
            }
        }
        return false;
    }

But I dont want to do this for all the APIS of redis dao, Is there any better way to handle exception.

Upvotes: 0

Views: 271

Answers (2)

Piotr Podraza
Piotr Podraza

Reputation: 2029

You can achieve it with aspects and @AfterThrowing annotation.

First make sure you allowed Spring to use aspects using @EnableAspectJAutoProxy annotation on any of your configuration classes.

Then define an @Aspect class with method annotated with @AfterThrowing like this:

@Aspect
public class GenericExceptionHandler {

    // you can use more specific path here
    @AfterThrowing ("execution(* *.*(..))", throwing = "ex")
    public void handleException(Exception ex) throws Exception { 
          // handle the exception here
     }

}

Upvotes: 0

Nishant Bhardwaz
Nishant Bhardwaz

Reputation: 1001

You can use @RestControllerAdvice. Make a custom exception class CustomRedisException throw CustomRedisException Exception from every controller and handle this in separate class annotated with @RestControllerAdvice.

@Override 
public boolean delMyStatus(String key) {
    try{
        return  redisTemplate.delete(key);
    }
    catch (Exception e){
        if(e.getCause() != null && e.getCause().getCause() instanceof RedisException) {      RedisException ex = (RedisException)e.getCause().getCause();
           throw new CustomRedisException(ex);
        } else {
            throw new IllegalStateException("...");
        }
    }
    return false;
}

Make GlobalExceptionHandler like below.

@RestControllerAdvice(basePackages = "your base package here", basePackageClasses = RepositoryRestExceptionHandler.class)
public class GlobalRestExceptionHandler {

    @ExceptionHandler
    public ResponseEntity<ErrorResponse> handleCustomException(final CustomRedisExceptionex) {

        // code for exception handling here.

        return new ResponseEntity<>(
                new ErrorResponse(HttpStatus.PRECONDITION_FAILED.value(), ex.getMessage()),
                HttpStatus.PRECONDITION_FAILED);
    }
}

Upvotes: 1

Related Questions