SpringMVC framework | custom exception handler


A custom exception handler Introduction

During the development of software coding, in other business logic layer up just to throw an exception to that: dao ---> service --->controlerFinally, an exception to the controller layer must be dealt with, it may be an exception to the unified exception handler.

Advantages : the ability to reduce duplication of code complexity and help maintain code.

Second, the test custom exception handler

The following code demonstrates throwing an exception, the test uses a custom exception handler for processing.

1. Packaging custom exception information

Class requires custom exception information 继承Exception类, a message attribute, a reference structure, and a corresponding set and get methods.

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. exception resolvers

Exception resolvers need 实现HandlerExceptionResolver接口the exception into a custom exception is bound to the request scope, an exception is forwarded to the interface.

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. Add to the bean configuration 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. The final jump page

Error 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>

No error 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. Test page

Were tested code throws a custom exception or system anomalies.

Encounter custom exception

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

Program execution to go if branch instructions detected is a custom exception information,
Here Insert Picture Description
Here Insert Picture Description

The system comes with experience abnormal

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

Here Insert Picture Description

Custom exception handler end of the test.

Published 424 original articles · won praise 1122 · Views 250,000 +

Guess you like

Origin blog.csdn.net/weixin_43691058/article/details/104415762