SpringMVC之异常处理
异常分为编译时异常和运行时异常,编译时异常我们trycatch捕获,捕获后自行处理,而运行时异常是不可预期的,就需要规范编码来避免,在SpringMVC中,不管是编译异常还是运行时异常,都可以最终由SpringMVC提供的异常处理器进行统一管理,这样就可以避免随时随地捕获异常的繁琐性。
文章来源:https://www.toymoban.com/news/detail-653533.html
三种处理方式
1.简单异常处理器:使用Spring MVC内置的异常处理器处理:SimpleMappingExceptionResolver
@Component public class MysimpleMappingExceton { @Bean public SimpleMappingExceptionResolver simpleMappingExceptionResolver(){ SimpleMappingExceptionResolver simpleMappingExceptionResolver = new SimpleMappingExceptionResolver(); //默认错误 simpleMappingExceptionResolver.setDefaultErrorView("default.html"); Properties properties = new Properties(); properties.setProperty("java.lang.ArithmeticExceotion","erro1.html"); properties.setProperty("java.io.FileNotFoundException","erro2.html"); simpleMappingExceptionResolver.setExceptionMappings(properties); return simpleMappingExceptionResolver; } }
2.自定义异常处理器:实现HandlerExceptionResolver接口,自定义异常进行处理
@Component public class MyHandlerExceptionResolver implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("/default.html"); return modelAndView; } }
3.使用@ControllerAdvice@ExceptionHandler实现全局异常
@ControllerAdvice public class GloExceotion { @ExceptionHandler(RuntimeException.class) @ResponseBody public Result runtimeException(){ Result result = new Result(200,"错误",new Object()); return result; } @ExceptionHandler(FileNotFoundException.class) public ModelAndView fileNotException(){ ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("/erro2.html"); return modelAndView; } @ExceptionHandler(Exception.class) public ModelAndView Exception(){ ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("/default.html"); return modelAndView; } }
例子文章来源地址https://www.toymoban.com/news/detail-653533.html
@RestController public class ExceptionController { @RequestMapping("/e1") public String e1 (){ int a=10/0; return "ruuning exception"; } @RequestMapping("/e2") public String e2() throws FileNotFoundException { FileInputStream fileInputStream = new FileInputStream("file:/barch:/"); return "ruuning exception"; } @RequestMapping("/e3") public String e3() { int [] array ={1,2}; System.out.println(array[5]); return "ruuning exception"; } }
到了这里,关于SpringMVC之异常处理 SpringMVC之异常处理的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!