13_SpringMVC_异常处理

时间:2023-02-26 12:59:35


 SpringMVC异常简介
系统中异常包括两类:预期异常(检查型异常)和运行时异常 RuntimeException,前者通过捕获异常从而获取异常信息, 后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。
系统的 dao、service、controller 出现都通过 throws Exception 向上抛出,最后由 springmvc 前端控制器交由异常处理器进行异常处理,如下图

 

异常处理具体实现

1使用@ExceptionHandler注解处理异常

缺点:只能处理当前Controller中的异常。

@Controller
public class ControllerDemo1 {
@RequestMapping("test1.action")
public String test1(){
int i = 1/0;
return "success.jsp";
}
@RequestMapping("test2.action")
public String test2(){
String s =null;
System.out.println(s.length());
return "success.jsp";
}
@ExceptionHandler(value ={ArithmeticException.class,NullPointerException.class} )
public ModelAndView handelException(){
ModelAndView mv =new ModelAndView();
mv.setViewName("error1.jsp");
return mv;
}
}

 

2使用:@ControllerAdvice+@ExceptionHandler

此处优先级低于局部异常处理器

package com.msb.exceptionhandler;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
/**
* @Author: Ma HaiYang
* @Description: MircoMessage:Mark_7001
*/
@ControllerAdvice
public class GloableExceptionHandler1 {
@ExceptionHandler(value ={ArithmeticException.class,NullPointerException.class} )
public ModelAndView handelException(){
ModelAndView mv =new ModelAndView();
mv.setViewName("error1.jsp");
return mv;
}
}

 配置包扫描

<context:component-scan base-package="com.msb.service,com.msb.exceptionhandler"/>

 

3使用:SimpleMappingExceptionResolver

 
xml配置
 

<!--自定义异常解析器-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.ArithmeticException">redirect:/error.jsp</prop>
<prop key="java.lang.NullPointerException">redirect:/error2.jsp</prop>
</props>
</property>
</bean>

 

配置类配置

/**
* 全局异常
*/
@Configuration
public class GloableException2 {
@Bean
public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver(){
SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
Properties prop = new Properties();
prop.put("java.lang.NullPointerException","error1.jsp");
prop.put("java.lang.ArithmeticException","error2.jsp");
resolver.setExceptionMappings(prop);
return resolver;
}
}

 

 

4自定义的HandlerExceptionResolver

/**
* 全局异常
* HandlerExceptionResolve
*/
@Configuration
public class GloableException3 implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
ModelAndView mv = new ModelAndView();
if(e instanceof NullPointerException){
mv.setViewName("error1");
}
if(e instanceof ArithmeticException){
mv.setViewName("error2");
}
mv.addObject("msg",e);
return mv;
}}