SpringMVC框架|自定义异常处理器


一、自定义异常处理器介绍

在进行软件开发编码时,在其他业务逻辑层只需要将异常向上抛出即可,即:dao ---> service --->controler,最后异常到controller层时就必须要处理了,可以将异常交给统一异常处理器处理。

优点:能够减少代码的重复度和复杂度,有利于代码的维护。

二、测试自定义异常处理器

下面的代码演示了抛出一个异常,测试使用自定义异常处理器进行处理。

1.封装自定义异常信息

自定义异常信息类需要继承Exception类提供一个message属性,一个有参构造,和对应的set与get方法。

package com.gql.ex;
/**
 * 类说明:
 *		自定义异常处理器
 * @guoqianliang1998.
 */
public class MyException extends Exception{
	
	private String message;

	public MyException(String message) {
		super();
		this.message = message;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
}

2.异常解析器

异常解析器需要实现HandlerExceptionResolver接口 ,将异常转换为自定义异常绑定到request作用域中,转发到异常界面。

package com.gql.ex;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

/**
 * 类说明: 
 * 		异常解析器 
 * @guoqianliang1998.
 */
public class MyHandlerExceptionResolver implements HandlerExceptionResolver {

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		MyException myEx = null;
		//如果是自己定义的异常
		if (ex instanceof MyException) {
			myEx = (MyException) ex;
		} 
		//如果是系统的异常,仍转换为自己的异常
		else {
			myEx = new MyException("您好,系统正在维护,请联系管理员!");
		}
		//将信息绑定到request作用域
		String message = myEx.getMessage();
		request.setAttribute("message", message);
		//转发到异常页面
		try {
			request.getRequestDispatcher("/WEB-INF/error.jsp").forward(request, response);
		} catch (ServletException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new ModelAndView();
	}
}

3.添加bean到SpringMVC配置中

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	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/aop
		http://www.springframework.org/schema/aop/spring-aop.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 ">
	
	<!-- 处理器(手写) -->
	<context:component-scan base-package="com.gql.upload"></context:component-scan>
	
	<!-- 代替处理器映射器和处理器适配器 -->
	<mvc:annotation-driven/>

	<!-- 视图解析器 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/product/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
	
	<!-- 自定义异常解析器 -->
	<bean id="myHandlerExceptionResolver" class="com.gql.ex.MyHandlerExceptionResolver">
	
	</bean>
		
</beans>

4.最终跳转页面

出现错误error.jsp

<%@ page language="java" import="java.util.*" 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>

没有错误success.jsp

<%@ page language="java" import="java.util.*" 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>
    	用户添加成功.
  </body>
</html>

5.测试页面

分别测试代码中抛出一个自定义异常或者系统异常。

遇到自定义异常

package com.gql.upload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.gql.ex.MyException;
import com.gql.pojo.User;

/**
 * 类说明:
 *		测试异常处理器
 * @guoqianliang1998.
 */
@Controller
@RequestMapping("/user")
public class UserController {
	
	@RequestMapping("/add")
	public String add(User user) throws MyException{
		if(true){
			throw new MyException("添加用户失败");//自定义异常
		}
		return "success";
	}
}

程序执行,走了if分支,说明检测到了是自定义的异常信息,
在这里插入图片描述
在这里插入图片描述

遇到系统自带异常

	@RequestMapping("/add")
	public String add(User user) throws MyException{
		int i = 1/0;//系统自带的异常
		return "success";
	}

在这里插入图片描述

自定义异常处理器测试结束。

发布了424 篇原创文章 · 获赞 1122 · 访问量 25万+

猜你喜欢

转载自blog.csdn.net/weixin_43691058/article/details/104415762