SpringMVC---异常的处理

使用场景:当浏览器向浏览器发送请求,而服务器处理请求出现了异常的状况,若是直接把错误信息给浏览器展现出来是很很差的,由于用户就能看到具体的代码错误信息。因此当出现异常状况时,服务器能够给用户一个本次请求异常的页面,让用户知道当前服务器有点问题,请稍后再试。spring

实现流程

  • 1)自定义异常类
public class MyException  extends RuntimeException{
     private String message;
     public MyException(){}
     public MyException(String message){
        this.message = message;
     }
     public void setMessage(String message) {
        this.message = message;
     }
     @Override
     public String getMessage() {
        return message;
     }
}
  • 2)自定义异常处理类,处理咱们抛出的异常浏览器

    • 对于异常的处理,我是把它转发到一个error页面,这里你们能够本身建立一个
@Component
public class ExceptionResolver implements HandlerExceptionResolver {
     @Override
     public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        if (e instanceof MyException){
                    ModelAndView mv = new ModelAndView();
         mv.addObject("errorMessage", e.getMessage());
         mv.setViewName("error.jsp");
         return mv;
        }
        return null;
     }
}
  • Controller类:这里是捕获了一个空指针异常,而后抛出了咱们自定义的异常
@Controller
public class UserController {
     @RequestMapping("testException.do")
     public String testException(){
     try {
            String str = null;
            str.length();
     }catch (NullPointerException e){
            e.printStackTrace();
            throw new MyException("服务器繁忙,请稍后再试!!!");
     }
            return "testException.jsp";
     }
}
  • ApplicationContext.xml(Spring核心配置文件)配置信息以下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 开启spring注解驱动-->
 <context:component-scan base-package="com.cjh"/>
<!-- 开启mvc注解驱动-->
 <mvc:annotation-driven></mvc:annotation-driven>

</beans>
相关文章
相关标签/搜索