spring 或 springboot统一异常处理

spring 或 springboot统一异常处理
https://blog.csdn.net/xzmeasy/article/details/76150370

一,本文介绍spring MVC的自定义异常处理,即在Controller中抛出自定义的异常时,客户端收到更友好的JSON格式的提示。而不是常见的报错页面。

二,场景描述:实现公用API,验证API key的逻辑,放在拦截器中判断(等同于在Controller中)并抛出异常,用户收到类似下图的提示:

其中,Http状态Code也能自由控制。

三,解决方案:

1,在RateLimitInterceptor.Java拦截器中抛出异常:

[java]  view plain  copy
 
 
 
  1. public class RateLimitInterceptor extends HandlerInterceptorAdapter{  
  2.   
  3.     @Autowired private RedisService rs;  
  4.   
  5.     /** 
  6.      * 流量控制检查入口 
  7.      */  
  8.     @Override  
  9.     public boolean preHandle(HttpServletRequest request,  
  10.             HttpServletResponse response, Object handler) throws RequiredParameterException, SignException, RateLimitException,Exception {  
  11.         super.preHandle(request, response, handler);  
  12.         String appKey = request.getParameter("appKey");  
  13.         //判断appKey是否为空或是否合法  
  14.         if(appKey == null){  
  15.             throw new RequiredParameterException("");  
  16.         }else if(AppKeyUtils.isFormatCorrect(appKey) || !rs.isExist(appKey)){  
  17.               
  18.             throw new SignException();  
  19.               
  20.         }else {  
  21.             try {  
  22.                 AppCall appCall = AppCall.create(appKey, AppKeyUtils.getPlanDetails(appKey));  
  23.                 appCall.decrease();  
  24.                 rs.save(appCall);  
  25.                 System.out.println("RateLimitInterceptor pass.");  
  26.             } catch (RateLimitException e) {  
  27.                 //抛出超限异常  
  28.                 throw new RateLimitException();  
  29.             }  
  30.         }  
  31.         return true;  
  32.     }  
  33.   
  34. }  

猜你喜欢

转载自www.cnblogs.com/chengjun/p/9234562.html