• 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. }  
  • 相关阅读:
    Kafka官方文档V2.7
    提交pr记录
    用Go语言来运行简单的hello world
    Mybatis学习记录-最简单的mybatis工程
    Flink CDC 实践记录
    CarbonDataDDL翻译003
    CarbonData使用案例
    CarbonData快速开始001
    如何构建数据仓库分层
    使用mybatis-plus的自动生成器生成代码
  • 原文地址:https://www.cnblogs.com/chengjun/p/9234562.html
Copyright © 2020-2023  润新知