springMvc自定义异常处理类

1.自定义异常类

	public class SysException extends Exception{
		// 存储提示信息的
		private String message;
		public String getMessage() {
			return message;
		}
		public void setMessage(String message) {
			this.message = message;
		}
		public SysException(String message) {
			this.message = message;
		}
	}

2.自定义异常处理器
注意:这里ModelAndView用于封装错误信息和返回的数据的

public class SysExceptionResolver implements HandlerExceptionResolver{
		public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
			// 获取到异常对象
			SysException e = null;
			if(ex instanceof SysException){
				e = (SysException)ex;
			}else{
				e = new SysException("系统正在维护....");
			}
			// 创建ModelAndView对象
			ModelAndView mv = new ModelAndView();
			mv.addObject("errorMsg",e.getMessage());
			mv.setViewName("error");
			return mv;
		}
	}

3.配置文件中配置异常处理器

	<?xml version="1.0" encoding="UTF-8"?>
	<beans xmlns="http://www.springframework.org/schema/beans"
		   xmlns:mvc="http://www.springframework.org/schema/mvc"
		   xmlns:context="http://www.springframework.org/schema/context"
		   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		   xsi:schemaLocation="
			http://www.springframework.org/schema/beans
			http://www.springframework.org/schema/beans/spring-beans.xsd
			http://www.springframework.org/schema/mvc
			http://www.springframework.org/schema/mvc/spring-mvc.xsd
			http://www.springframework.org/schema/context
			http://www.springframework.org/schema/context/spring-context.xsd">
		<!-- 开启注解扫描 -->
		<context:component-scan base-package="com.b3a4a"/>
		
		<!-- 视图解析器对象 -->
		<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
			<property name="prefix" value="/WEB-INF/pages/"/>
			<property name="suffix" value=".jsp"/>
		</bean>
		
		<!--前端控制器,哪些静态资源不拦截-->
		<mvc:resources location="/js/" mapping="/js/**"/>

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

		<!-- 开启SpringMVC框架注解的支持 -->
		<mvc:annotation-driven />
	</beans>

4.测试controller

@Controller
	@RequestMapping("/error")
	public class ExceptionController {
		@RequestMapping("/testException")
		public String testException() throws SysException{
			System.out.println("testException执行了...");
			try {
				// 模拟异常
				int a = 10/0;
			} catch (Exception e) {
				// 打印异常信息
				e.printStackTrace();
				// 抛出自定义异常信息
				throw new SysException("查询所有用户出现错误了...");
			}
			return "success";
		}
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值