更好的处理异常方法是Spring-boot



我有十个API,可以与Redis对话以存储数据。

当前它正在抛出嵌套的异常,所以我像以下那样做了以下嵌套的例外。

    @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;
    }

,但我不想为Redis Dao的所有API做到这一点,是否有更好的方法来处理异常。

您可以使用@RestControllerAdvice。从每个控制器中进行自定义异常类CustomRedisException抛出CustomRedisException异常,并在用@RestControllerAdvice注释的单独的class中处理。

@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;
}

使GlobalexceptionHandler如下。

@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);
    }
}

您可以通过方面和@AfterThrowing注释来实现它。

首先确保您允许Spring在任何配置类上使用@EnableAspectJAutoProxy注释使用方面。

然后用@AfterThrowing以这样的方法定义@Aspect类:

@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
     }
}

最新更新