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>
相關文章
相關標籤/搜索