Spring MVC exception handler

Keywords: Spring xml Java

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:

To use the exception handler provided by spring MVC:

(1) write an exception handling class to implement the HandlerExceptionResolver interface

(2) configure the exception handling class in the springmvc.xml file

(3) when the program throws an exception to the dispatcher servlet, the exception handling class will be executed automatically.

Throwing exceptions can be executed by the program itself, or custom exceptions can be thrown through the throw keyword.

 

Example: throwing custom exception execution exception handler

Custom exception:

package club.ityuchao.exception;

public class MyException extends Exception {

	private String message;

	public MyException() {
		super();
	}

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

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

Exception handler write:

package club.ityuchao.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

public class CustomerExceptionResolver implements HandlerExceptionResolver {

	/**
	 * Object Save the method declaration of the method throwing the exception
	 */
	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj,
			Exception e) {
		String message = null;
		if(e instanceof MyException) {
			message = e.getMessage();
		} else {
			message = e.toString() + e.getMessage();
		}
		
		ModelAndView mav = new ModelAndView();
		mav.addObject("message", message);
		mav.setViewName("message");
		return mav;
	}

}

spring management exception handler:

<!-- Exception handler -->
<bean class="club.ityuchao.exception.CustomerExceptionResolver"/>

Program running exception:

@RequestMapping(value="/updateitem.action")
	public String updateItem(Items item, Model model) throws Exception {
		
		ItemService.updateItem(item);
		
		if(true) {
			throw new MyException("Custom exception");
		}
		
		//int i = 1/0;
		
		return "redirect:/item/itemlist.action";
	}

Page display error message:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	${message }
</body>
</html>

RuntimeException:

Custom exception:

Posted by nihal on Tue, 29 Oct 2019 09:17:15 -0700