SpringBoot自己默认的异常处理机制。 自己定义的异常 1.在templates下建立一个error页面,注意名字只能是error。才能在不更改默认配置的情况下跳转到自己所定义的异常处理界面。
@RequestMapping("/testError") public String testError() { int i=10/0; return "add"; }2.在@Controller条件下在增加一个注解 @ExceptionHandler(value = {java.lang.ArithmeticException.class})
@ExceptionHandler(value = {java.lang.ArithmeticException.class}) public ModelAndView arithmeticExceptionHandler(Exception e){ ModelAndView mv = new ModelAndView(); mv.addObject("error",e.toString()); mv.setViewName("error1"); return mv; }3.自定义一个全局配置文件,对异常进行设置。注意在类名上的注解是@ControllerAdvice,与第二个不一样,也是一种升级。@ControllerAdvice+@ExceptionHandler方式进行异常处理。
@ControllerAdvice public class Exception { @ExceptionHandler(value = {java.lang.ArithmeticException.class}) public ModelAndView arithmeticExceptionHandler(java.lang.Exception e){ ModelAndView mv = new ModelAndView(); mv.addObject("error",e.toString()); mv.setViewName("error1"); return mv; } } .自定义一个全局配置文件,对异常进行设置。用@Configuration,告诉springboot,这是一个配置文件,并在方法上对SimpleMappingExceptionResolver这个类进行进行@Bean标记。mapping的put()方法中,第一个参数为异常的错误类型,第二个参数是映射跳转的界面路径! @Configuration public class SimpleMappingExceptionHandler { @Bean public SimpleMappingExceptionResolver exceptionResolver(){ SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver(); Properties mappings =new Properties(); mappings.put("java.lang.ArithmeticException","error1"); resolver.setExceptionMappings(mappings); return resolver; } }5.建立HandlerException 这个类,并实现HandlerExceptionResolver 这个接口。重写这个接口中的ModelAndView类型的 resolveException方法,并用if()条件语句进行异常类型的跳转和setViewName跳转错误页面的路径书写。
@Configuration public class HandlerException implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, java.lang.Exception e) { ModelAndView modelAndView =new ModelAndView(); if(e instanceof ArithmeticException){ modelAndView.setViewName("error1"); } return modelAndView; } }