SpringBoot學習(三)
阿新 • • 發佈:2018-12-12
異常處理
一、模擬異常
修改HelloController,使得訪問/hello一定會產生異常: some exception
package com.zyj.blog.web; import java.text.DateFormat; import java.util.Date; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; /** * @author zyj * */ @Controller public class HelloController { @RequestMapping("/hello") public String hello(Model m) throws Exception { m.addAttribute("now",DateFormat.getDateTimeInstance().format(new Date())); if(true){ throw new Exception("some exception"); } return "hello"; } }
二、新增一個異常處理類
新增加一個類GlobalExceptionHandler,用於捕捉Exception異常以及其子類。捕捉到之後,把異常資訊,發出異常的地址放進ModelAndView裡,然後跳轉到 errorPage.jsp
package com.zyj.blog.exception; import javax.servlet.http.HttpServletRequest; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView; /** * @author zyj * */ @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(value = Exception.class) public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception { ModelAndView mav = new ModelAndView(); mav.addObject("exception", e); mav.addObject("url", req.getRequestURL()); mav.setViewName("errorPage"); return mav; } }
三、錯誤頁面
errorPage.jsp 格式化一下,稍微好看點顯示這些異常資訊
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <div style="width:500px;border:1px solid lightgray;margin:200px auto;padding:80px"> 系統 出現了異常,異常原因是: ${exception} <br><br> 出現異常的地址是: ${url} </div>