Spring异常解析器HandlerExceptionResolver
一、spring异常解析器
1. 为什么使用:系统产生的异常,如果没被捕获,会返回给客户端,用户会看到看不懂的异常信息,体验不好
2. 作用:全局异常捕获,统一处理异常
3. HandlerExceptionResolver接口
public interface HandlerExceptionResolver { @Nullable ModelAndView resolveException(HttpServletRequest var1, HttpServletResponse var2, @Nullable Object var3, Exception var4); }
二、定义自己的异常解析器,实现HandlerExceptionResolver
@Component @Slf4j public class BusinesExceptionHandler implements HandlerExceptionResolver { private static String errorMsg = "服务器繁忙,请稍后尝试"; private static String nullErrorMsg = "null"; @Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView()); modelAndView.addObject("message", msg); modelAndView.addObject("code", code); return modelAndView; } }
三、把自定义的异常解析器,注册到异常解析器列表
@Configuration @Slf4j public class InterceptorConfig implements WebMvcConfigurer { @Override public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) { resolvers.add(new BusinesExceptionHandler()); } }
参考:
https://blog.csdn.net/qq_22172133/article/details/82147630
https://www.cnblogs.com/taiguyiba/p/11817930.html
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步