SpringMVC exception handling (with code)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/weixin_44296929/article/details/102568498

A, Java Exception system :( Photo from Internet)
Here Insert Picture Description
1. In these exceptions, RuntimeExceptionits descendants, abnormal, do not have to deal with in the Java syntax, for two main reasons: the frequency of these anomalies may appear very high, if must be tackled, such as: try...catch, almost all the code needs to be put try代码块in, and can put an end to these anomalies are abnormal, through rigorous programming, we can ensure that these anomalies will never happen!
2, handle exceptions in two ways: using the try...catchhandle exceptions, or use the throwthrown objects, and used in the method statement throwssyntax for declaring throw!
3. Generally, exceptions are to be handled, if there is no exception handling, can cause abnormal continue to throw up, eventually java EE anomalies will be made Tomcatto deal with, the trace log will appear on the page, the pages will look very not friendly and there is risk analysis of the project's content, for the follow-up to solve the problem and there is no help, so in principle, it must handle exceptions!
4, 非RuntimeExceptionis the limit from the syntax processing requirements, so each call to a method throws an exception, we must continue to try ... catch or throw statement! (This is not to say)
5, RuntimeExceptionand its descendant classes anomaly is not syntactically mandatory treatment, but, once there, security, user experience in all aspects of the project will have a negative impact.

Second, let's look at it in SpringMVC way to handle exceptions:

1, the processing exception -SimpleMappingExceptionResolver:
SPRINGMVC provides a unified way to handle exceptions: using SimpleMappingExceptionResolverclass, by private Properties exceptionMappings;configuring the corresponding relationship between the anomaly category attribute forwarded to the page, i.e. each abnormality can have a corresponding page of Once the abnormal configuration had appeared project will be routed to the corresponding page to an error message!
Note: This is very simple way to handle exceptions, however, there is also a larger question: Can not prompt for more information! For example: ArrayIndexOutOfBoundsException occurs when, in fact, an exception also encapsulates the detailed error information, namely: What is the value of cross-border and so on.

<!-- 配置统一处理异常 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
	<property name="exceptionMappings">
		<props>
			<prop key="java.lang.RuntimeException">runtime</prop>
			<prop key="java.lang.NullPointerException">null</prop>
			<prop key="java.lang.ArrayIndexOutOfBoundsException">index</prop>
		</props>
	</property>
</bean>

By the above configuration, in the event NullPointerException will jump to null.jsp page.

2, the processing exception - @ ExceptionHandler Note:
can be defined in a method of the controller class to handle exceptions, before the method is added @ExceptionHandler, and then, within the agreed terms of all abnormal, can be determined by the method of how to handle:

@ExceptionHandler
public String handleException(Exception e) {
	System.out.println(
		"ExceptionController.handleException()");
		
	if (e instanceof NullPointerException) {
		return "null";
	} else if (e instanceof ArrayIndexOutOfBoundsException) {
		return "index";
	}
		
	return "runtime";
}

An exception is processed, if the data needs to be forwarded, may be modified as the return value ModelAndView, or added in the parameter list a method of handling an exception HttpServletRequest, however, not be used ModelMapto encapsulate data transferred:

@ExceptionHandler
public String handleException(Exception e,
		HttpServletRequest request) {
	System.out.println(
		"ExceptionController.handleException()");
		
	if (e instanceof NullPointerException) {
		return "null";
	} else if (e instanceof ArrayIndexOutOfBoundsException) {
		request.setAttribute("msg", e.getMessage());
		return "index";
	}
		
	return "runtime";
}

Example: Let's give a small example to understand:
For example, we want to write a UserController, the user name in the Controller handles user submitted when they were occupied, Thrown.
step1, first create a base class BaseController controller.

public abstract class BaseController {
	@ExceptionHandler(RuntimeException.class)
	@ResponseBody
	public ResponseResult<Void> handleException(Exception e){
		//判断类型,并进行处理
		if(e instanceof UsernameConflictException){
			//用户名冲突异常
			return new ResponseResult<Void>(401,e);
		}
	}
}

step2, then we create UserController we handle business logic, let UserController inherit our BaseController.

@Controller
@RequestMapping("/user")
public class UserController extends BaseController{
	@Autowired
	private IUserService userService;
	
	//调用业务层进行注册(reg为接口)
	userService.reg(user);
	//执行返回
	return new ResponseResult<Void>();
}

step3, reg interface code: Let me just give you an example of the exception, certainly more than the actual development of this kind of anomalies.

public interface IUserService {
	User reg(User user)throws UsernameConflictException;
}

Look specific business layer implementation class: thrown exception, and the abnormality information are defined:throw new UsernameConflictException("");

@Service("userService")
public class UserServiceImpl implements IUserService{
	@Autowired
	private UserMapper userMapper;
	
	public User reg(User user) throws UsernameConflictException,InsertDataException{
		// 根据尝试注册的用户名查询用户数据
		User data=findUserByUsername(user.getUsername());
		// 判断是否查询到数据
		if(data!=null){
			// 是:查询到数据,即用户名被占用,则抛出UsernameConflictException异常
			throw new UsernameConflictException("用户名("+user.getUsername()+")已被占用");
		}else{
			// 否:没有查询到数据,即用户名没有被占用,则执行插入用户数据,获取返回值
			User result=insert(user);
			// 执行返回
			return result;
		}
	}

Step4, the page corresponding to the request ajax: If the returned status code 401, will be prompted an error message.

<script type="text/javascript">
	$("#btn-reg").click(function(){
		var url="../user/handle_reg.do";
		var data=$("#reg-form").serialize();
		$.ajax({
			"url":url,
			"data":data,
			"type":"POST",
			"dataType":"json",
			"success":function(json){
				if(json.state==401){
					//用户名已被占用
					alert("注册失败"+json.message);
				}
			}
		});
	});
</script>

Third, think about:

1, you can add 3 BaseController method of treating an abnormality in the class, separately processing NullPointerExceptionand ArrayIndexOutOfBoundsExceptionand RuntimeExceptionabnormal?
Answer: Yes! It allows the use of a plurality of different methods to handle exceptions!

2, assuming A method of treating an abnormality in the controller, when an abnormality occurs in the processing request controller B, it will be processed?
The answer: No! Typically, you create a BaseController, as the current controller base class project, then, to write code to handle exceptions in this class can be!

3, on @ExceptionHandler, may also be used to limit the types of abnormalities of the corresponding method of treatment!
E.g:@ExceptionHandler(IndexOutOfBoundsException.class);

The following code represents the above method for processing only IndexOutOfBoundsExceptionits descendants, exception handling and other anomalies are not!

IV Summary:

1, the essence can not handle exceptions 撤销exceptions, can not let the problem has been reduced to no problems arise, so that the nature of handling exceptions should try to remedy problems that have emerged, and try to tell the user through prompts, etc. , try to do the right thing, to avoid the follow-up the same problem again!
2, For developers, should deal with every possible exception, because, if not treated, will continue to throw, finally captured Tomcat, and Tomcat way is to deal with anomalous trace information displayed on the page, It is extremely inappropriate!
3, in SpringMVC, the processing abnormalities in two ways, first by SimpleMappingExceptionResolversetting a corresponding relationship between abnormal and forwarding target, the second species are used @ExceptionHandlerto annotate a method of handling exceptions is recommended to use the second aspect.
4, typically, the method will handle exceptions written in the base class control project, i.e. written in BaseController in use @ExceptionHandler, the abnormality can be clearly specify the type of treatment, for example: @ExceptionHandler(NullPointerException)and, in the controller class, may be prepared by multiple methods to handle exceptions.
5, relates to a method to handle exceptions, should be the publicmethod, the same return type and the processing request mode may be Stringor ModelAndViewor other approved type, name of the method can be customized, the argument list must contain the Exceptiontypes of parameters, also allows HttpServletRequest, HttpServletResponse, It is not allowed ModelMap.

Above is the Spring MVC way to handle exceptions, if article helpful to you, please support a praise, thank you.

Guess you like

Origin blog.csdn.net/weixin_44296929/article/details/102568498