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"; }

相关推荐
csdn_aspnet5 分钟前
javascript 算法 LeetCode 编号 70 - 爬楼梯
开发语言·javascript·算法·leetcode·ecmascript
shehuiyuelaiyuehao11 分钟前
多线程入门
java·python·算法
Navigator_Z14 分钟前
LeetCode //C - 1073. Adding Two Negabinary Numbers
c语言·算法·leetcode
醇氧20 分钟前
【OpenClaw】更换阿里百炼完整配置指南
算法·ai
Tina学编程30 分钟前
[HOT100]每日一练------最长连续序列
算法·hot 100
大明者省44 分钟前
IIS 端口绑定正常访问的原理说明与常见误区澄清
运维·服务器·笔记
tedcloud1231 小时前
ai-engineering-from-scratch部署教程:从零搭建AI应用环境
服务器·前端·人工智能·系统架构·edge
csdn_aspnet1 小时前
PHP 算法 LeetCode 编号 70 - 爬楼梯
算法·leetcode·php
mounter6251 小时前
迈向硬件级无缝热升级:Linux 内核 VFIO 与 IOMMU 持久化技术的演进之路
linux·服务器·内存管理·kernel
晚风吹红霞1 小时前
Linux软件包管理器详解 —— yum与apt的使用及软件生态
linux·运维·服务器