brief introduction
Spring MVC exception information in the process of processing the request is handled by the exception handler. The custom exception handler can implement the exception handling logic of a system.
Abnormal understanding
Exceptions include compile time and run-time exceptions, where compile time exceptions are also called expected exceptions. Runtime exceptions are found only when the project is running, and they don't need to be concerned when compiling.
Runtime exceptions, such as null pointer exceptions and array out of bounds exceptions, can only be solved by programmers' rich experience and testers' continuous strict testing.
Compile time exceptions, such as database exceptions, file read exceptions, custom exceptions, etc. For such an exception, you must use the try catch code block or the throws keyword to handle the exception.
Abnormal handling ideas
There are two types of exceptions in the system: expected exception (compile time exception) and runtime exception. The former obtains exception information by catching exceptions, while the latter reduces the occurrence of runtime exceptions by standardizing code development and testing.
The dao, service and controller of the system are all thrown upward through throws Exception. Finally, the spring MVC front-end controller hands over to the exception processor for exception handling, as shown in the following figure:
There is only one exception handler in the global scope.
Custom exception class
Step 1: CustomException.java
package com.cyb.ssm.exception; /** * Custom compile time 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; } }
Step 2: customexceptionresolver.java (key)
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=""; // Exception handling logic if (ex instanceof CustomException) { message = ((CustomException) ex).getMsg(); } else { message="unknown error"; } ModelAndView mv=new ModelAndView(); mv.setViewName("error"); mv.addObject("message", message); return mv; } }
Step 3: add bean s to springmvc.xml
<?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"> <!-- Scan of processor class --> <context:component-scan base-package="com.cyb.ssm.controller"></context:component-scan> <mvc:annotation-driven conversion-service="conversionService"/> <!-- Display configuration view resolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- Configure custom transformation services --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <!-- Custom date type converter --> <bean class="com.cyb.ssm.controller.converter.DateConverter"></bean> </set> </property> </bean> <!-- Configure exception handler --> <bean class="com.cyb.ssm.resolver.CustomExceptionResolver"></bean> </beans>
Step 4: jsp error page
<%@ 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>Error page</title> </head> <body> ${message } </body> </html>
Step 5: test class
@RequestMapping("queryItem") public ModelAndView queryItem() throws CustomException { //Querying database, simulating with static data List<Item> itemList = Service.queryItemList(); ModelAndView mvAndView = new ModelAndView(); mvAndView.addObject("itemList", itemList); //Set view(Logical path) mvAndView.setViewName("item/item-list"); if (true) { throw new CustomException("I am a custom exception class"); } return mvAndView; }
Realization
Source code
Full code: Direct download