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