SSM异常处理

1.配置错误页面 404.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>主页</title> </head> <body> <html> <body> <h1><b th:text="${errorMsg}"></b></h1> </body> </html>

2.自定义异常处理器

package com.qcby.util; import com.qcby.entity.SysException; 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) { e.printStackTrace(); //在命令行打印异常信息在程序中出错的位置及原因。 // 做强转 SysException exception = null; // 判断 if(e instanceof SysException){ exception = (SysException)e; }else{ exception = new SysException("系统正在维护,请联系管理员"); } ModelAndView mv = new ModelAndView(); mv.addObject("errorMsg",exception.getMessage()); // 设置跳转的页面 mv.setViewName("404"); return mv; } }

3.自定义异常类

/** * 异常处理类 */ public class SysException extends Exception{ // 提示消息 private String message; public SysException(String message){ this.message = message; } @Override public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public String toString() { return "SysException{" + "message='" + message + '\'' + '}'; } }

4.配置异常处理器

<!--配置异常处理器--> <bean id="sysExceptionResolver" class="com.qcby.util.SysExceptionResolver" />

5.Controller测试

/** * 使用异常处理器方式 * @return */ @RequestMapping("/findAll.do") public String findAll(){ System.out.println("执行了..."); // 模拟异常 int a = 10/0; return "suc"; }

相关推荐
安科士andxe14 小时前
深入解析|安科士1.25G CWDM SFP光模块核心技术,破解中长距离传输痛点
服务器·网络·5g
寻寻觅觅☆17 小时前
东华OJ-基础题-106-大整数相加(C++)
开发语言·c++·算法
偷吃的耗子17 小时前
【CNN算法理解】:三、AlexNet 训练模块(附代码)
深度学习·算法·cnn
2601_9491465318 小时前
Shell语音通知接口使用指南:运维自动化中的语音告警集成方案
运维·自动化
儒雅的晴天18 小时前
大模型幻觉问题
运维·服务器
化学在逃硬闯CS18 小时前
Leetcode1382. 将二叉搜索树变平衡
数据结构·算法
ceclar12318 小时前
C++使用format
开发语言·c++·算法
Gofarlic_OMS19 小时前
科学计算领域MATLAB许可证管理工具对比推荐
运维·开发语言·算法·matlab·自动化
通信大师19 小时前
深度解析PCC策略计费控制:核心网产品与应用价值
运维·服务器·网络·5g
dixiuapp19 小时前
智能工单系统如何选,实现自动化与预测性维护
运维·自动化