HDUoj-------(1128)Self Numbers
阿新 • • 發佈:2022-05-05
分析
為防止異常直接顯示在瀏覽器上,我們需要一個異常處理器,轉到錯誤提示頁面。
實現
1.編寫自定義異常類(做提示資訊的)
package com.czy.exception; /** * 自定義異常類 */ public class SysException extends Exception{ //儲存提示資訊 private String message; public SysException(String message){ setMessage(message); } @Override public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
2.捕獲異常並丟擲自定義異常
@RequestMapping("/testException") public String testException() throws Exception{ System.out.println("testException執行了..."); try { //模擬異常 int a = 10/0; } catch (Exception exception) { //列印異常資訊 exception.printStackTrace(); //丟擲自定義異常資訊 throw new SysException("查詢所有使用者出現錯誤..."); } return "success"; }
3.編寫異常處理器
package com.czy.exception; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class SysExceptionResolver implements HandlerExceptionResolver { /** * 處理異常業務邏輯 * @param httpServletRequest * @param httpServletResponse * @param o 異常處理器 * @param e 丟擲的異常 * @return */ @Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { //獲取異常物件 SysException sysException = null; if(e instanceof SysException) sysException = (SysException)e; else sysException = new SysException("系統正在維護"); ModelAndView mv = new ModelAndView(); mv.addObject("errorMsg",sysException); mv.setViewName("error"); return mv; } }
4.編寫提示資訊頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${errorMsg.message}
</body>
</html>
5.配置異常處理器(跳轉到提示頁面)
<!--配置異常處理器-->
<bean id="sysExceptionResolver" class="com.czy.exception.SysExceptionResolver"></bean>