深圳外贸网站怎么建,南阳做网站推广,免费php企业网站,百度举报网站SpringMVC之异常处理 异常分为编译时异常和运行时异常#xff0c;编译时异常我们trycatch捕获#xff0c;捕获后自行处理#xff0c;而运行时异常是不可预期的#xff0c;就需要规范编码来避免#xff0c;在SpringMVC中#xff0c;不管是编译异常还是运行时异常#xff…SpringMVC之异常处理 异常分为编译时异常和运行时异常编译时异常我们trycatch捕获捕获后自行处理而运行时异常是不可预期的就需要规范编码来避免在SpringMVC中不管是编译异常还是运行时异常都可以最终由SpringMVC提供的异常处理器进行统一管理这样就可以避免随时随地捕获异常的繁琐性。 三种处理方式
1.简单异常处理器使用Spring MVC内置的异常处理器处理SimpleMappingExceptionResolver Component
public class MysimpleMappingExceton {Beanpublic 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 {Overridepublic ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {ModelAndView modelAndView new ModelAndView();modelAndView.setViewName(/default.html);return modelAndView;}
} 3.使用ControllerAdviceExceptionHandler实现全局异常 ControllerAdvice
public class GloExceotion {ExceptionHandler(RuntimeException.class)ResponseBodypublic 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;}
} 例子 RestController
public class ExceptionController {RequestMapping(/e1)public String e1 (){int a10/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;}
}