【问题标题】:Better way to handle exception is spring-boot处理异常的更好方法是 spring-boot
【发布时间】:2019-03-11 13:18:15
【问题描述】:

我有一些与 redis 对话以存储数据的十个 API。

目前它正在抛出嵌套异常,所以我做了如下处理嵌套异常。

    @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都这样做,有没有更好的方法来处理异常。

【问题讨论】:

  • catch (RedisException e){}?
  • catch (RedisException e){ log.error("RedisException " + ex.getMessage()); } catch (Exception e){ log.error("Exception " + ex.getMessage()); } 这总是去异常块

标签: spring spring-boot exception


【解决方案1】:

您可以使用@RestControllerAdvice。为每个控制器创建一个自定义异常类 CustomRedisException throw CustomRedisException Exception,并在单独的 class 中处理此异常,并用 @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;
}

制作如下所示的 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);
    }
}

【讨论】:

  • 其实我不想把这个错误返回给rest-controller,是为了一些内部操作,所以我想在内部处理这个错误,并根据它做一些操作
  • 在这种情况下,您可以创建一个通用方法来处理异常并从每个 catch 块中调用它。
【解决方案2】:

你可以通过切面和@AfterThrowing注解来实现。

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

然后定义一个@Aspect 类,其方法用@AfterThrowing 注释,如下所示:

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

}

【讨论】:

  • 在此我想记录调用者发送的一些参数。那么如何将用户参数连同异常一起发送到@AfterThrowing 函数
猜你喜欢
  • 1970-01-01
  • 2016-06-12
  • 1970-01-01
  • 2018-11-07
  • 2023-03-28
  • 2016-11-10
  • 2021-02-22
  • 2015-02-23
  • 2016-09-29
相关资源
最近更新 更多