全国旗舰校区

不同学习城市 同样授课品质

北京

深圳

上海

广州

郑州

大连

武汉

成都

西安

杭州

青岛

重庆

长沙

哈尔滨

南京

太原

沈阳

合肥

贵阳

济南

下一个校区
就在你家门口
+
当前位置:首页  >  技术干货

如何使用Spring Boot实现异常处理?

发布时间:2022-09-22 11:51:57
发布人:wjy

  1. 使用@ExceptionHandler注解处理局部异常,该方式只能处理当前controller中的ArithmeticException和NullPointerException异常,缺点就是只能处理单个controller的异常。

  @Controller public class ExceptionHandlerController { @RequestMapping("/excep") public String exceptionMethod(Model model) throws Exception { String a=null; System.out.println(a.charAt(1)); int num = 1/0; model.addAttribute("message", "没有抛出异常"); return "index"; } @ExceptionHandler(value = {ArithmeticException.class,NullPointerException.class}) public String arithmeticExceptionHandle(Model model, Exception e) { model.addAttribute("message", "@ExceptionHandler" + e.getMessage()); return "index"; } }

如何使用Spring Boot实现异常处理

  2. 使用 @ControllerAdvice + @ExceptionHandler 注解处理全局异常 @ControllerAdvice public class ControllerAdviceException { @ExceptionHandler(value = {NullPointerException.class}) public String NullPointerExceptionHandler(Model model, Exception e) { model.addAttribute("message", "@ControllerAdvice + @ExceptionHandler :" + e.getMessage()); return "index"; } }

  3. 配置 SimpleMappingExceptionResolver 类处理异常 @Configuration public class SimpleMappingException { @Bean public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver(){ SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver(); Properties mappings = new Properties(); //个参数为异常全限定名,第二个为跳转视图名称 mappings.put("java.lang.NullPointerException", "index"); mappings.put("java.lang.ArithmeticException", "index"); //设置异常与视图映射信息的 resolver.setExceptionMappings(mappings); return resolver; } }

  4. 实现HandlerExceptionResolver接口处理异常@Configuration public class HandlerException implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("message", "实现HandlerExceptionResolver接口");

  //判断不同异常类型,做不同视图跳转 if(ex instanceof NullPointerException){ modelAndView.setViewName("index"); } if(ex instanceof ArithmeticException){ modelAndView.setViewName("index"); } return modelAndView; } }

相关文章

图卷积网络和self-attention有什么区别?

图卷积网络和self-attention有什么区别?

2023-10-15
深度学习模型权重h5、weights、ckpt、pth有什么区别?

深度学习模型权重h5、weights、ckpt、pth有什么区别?

2023-10-15
机器学习中Inference和predict的区别是什么?

机器学习中Inference和predict的区别是什么?

2023-10-15
kd-tree和ball-tree在算法实现原理上有什么区别?

kd-tree和ball-tree在算法实现原理上有什么区别?

2023-10-15

最新文章

常见网络安全面试题:Windows常用的命令有哪些?

常见网络安全面试题:Windows常用的命令有哪些?

2023-10-09
常见网络安全面试题:根据设备告警如何展开排查?

常见网络安全面试题:根据设备告警如何展开排查?

2023-10-09
常见网络安全面试题:mysql加固呢?(数据库加固)

常见网络安全面试题:mysql加固呢?(数据库加固)

2023-10-09
常见网络安全面试题:windows和linux加固?(操作系统加固)

常见网络安全面试题:windows和linux加固?(操作系统加固)

2023-10-09
在线咨询 免费试学 教程领取