SpringMvc 异常处理器
简介#
SpringMvc 在处理请求过程中出现异常信息由异常处理器进行处理,自定义异常处理器可以实现一个系统的异常处理逻辑。
异常理解#
异常包含编译时异常和运行时异常,其中编译时异常也叫预期异常。运行时异常只有在项目运行的情况下才会发现,编译的时候不需要关心。
运行时异常,比如:空指针异常、数组越界异常,对于这样的异常,只能通过程序员丰富的经验来解决和测试人员不断的严格测试来解决。
编译时异常,比如:数据库异常、文件读取异常、自定义异常等。对于这样的异常,必须使用 try catch代码块或者throws关键字来处理异常。
异常处理思路#
系统中异常包括两类:预期异常(编译时异常)和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试等手段减少运行时异常的发生。
系统的dao、service、controller出现都通过throws Exception向上抛出,最后由SpringMvc前端控制器交给异常处理器进行异常处理,如下图:
全局范围只有一个异常处理器。
自定义异常类#
第一步:CustomException.java#
package com.cyb.ssm.exception; /** * 自定义编译时异常 * * @author apple * */ public class CustomException extends Exception { private String msg; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public CustomException(String msg) { super(); this.msg = msg; } }
第二步:CustomExceptionResolver.java(重点)#
package com.cyb.ssm.resolver; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import com.cyb.ssm.exception.CustomException; public class CustomExceptionResolver implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { String message=""; // 异常处理逻辑 if (ex instanceof CustomException) { message = ((CustomException) ex).getMsg(); } else { message="未知错误"; } ModelAndView mv=new ModelAndView(); mv.setViewName("error"); mv.addObject("message", message); return mv; } }
第三步:在springmvc.xml中加入bean#
<?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:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 处理器类的扫描 --> <context:component-scan base-package="com.cyb.ssm.controller"></context:component-scan> <mvc:annotation-driven conversion-service="conversionService"/> <!-- 显示配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 配置自定义的转换服务 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <!-- 自定义日期类型转换器 --> <bean class="com.cyb.ssm.controller.converter.DateConverter"></bean> </set> </property> </bean> <!-- 配置异常处理器 --> <bean class="com.cyb.ssm.resolver.CustomExceptionResolver"></bean> </beans>
第四步:jsp错误页面#
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>错误页面</title> </head> <body> ${message } </body> </html>
第五步:测试类#
@RequestMapping("queryItem") public ModelAndView queryItem() throws CustomException { //查询数据库,用静态数据模拟 List<Item> itemList = Service.queryItemList(); ModelAndView mvAndView = new ModelAndView(); mvAndView.addObject("itemList", itemList); //设置视图(逻辑路径) mvAndView.setViewName("item/item-list"); if (true) { throw new CustomException("我是自定义异常类"); } return mvAndView; }
实现#
源码 #
完整代码:直接下载
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?