SpringMVC之異常處理
異常分為編譯時異常和運行時異常,編譯時異常我們trycatch捕獲,捕獲后自行處理,而運行時異常是不可預期的,就需要規(guī)范編碼來避免,在SpringMVC中,不管是編譯異常還是運行時異常,都可以最終由SpringMVC提供的異常處理器進行統(tǒng)一管理,這樣就可以避免隨時隨地捕獲異常的繁瑣性。
?文章來源:http://www.zghlxwxcb.cn/news/detail-653533.html
三種處理方式
1.簡單異常處理器:使用Spring MVC內(nèi)置的異常處理器處理: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.自定義異常處理器:實現(xiàn)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實現(xiàn)全局異常
@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; } }
例子文章來源地址http://www.zghlxwxcb.cn/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之異常處理的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!