springMVC exception handling

The exceptions in the system are generally divided into runtime exceptions and expected exceptions. In springMVC, the exceptions in the DAO, Controller, and Service layers are all thrown to the upper layer, and finally the front-end controller DispatcherServlet of springMVC is handed over to the global processor for processing. Exception handling.

The main functions implemented are as follows:

1. Analyze the type of exception and determine what kind of exception the exception belongs to

2. If the exception type is a system custom exception, directly extract the exception information and display it on the error page, if not, customize an exception class

3. Build an exception information display view, bind the exception information to the model, and then jump to the relevant exception display page

 

Take user login as an example

1. Customize a user login exception class, create a class named UserException, and inherit the Exception class

   

private String message;

public UserException(String message) {
// TODO Auto-generated constructor stub
super(message);
this.message=message;
}

public UserException() {
// TODO Auto-generated constructor stub
}

public String getMessage() {
return message;
}

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

2. Create a new class named UserExceptionResolve and implement the HandlerExceptionResolver interface

@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object obj, Exception exception) {
// TODO Auto-generated method stub
System.out.println("出现异常");
UserException ues = null;

if(exception instanceof UserException){
ues = (UserException) exception;
}else{
ues = new UserException("未知错误");
}

ModelAndView mav = new ModelAndView();
mav.addObject("message", ues.getMessage());
mav.setViewName("/error/userError");
return mav;
}

3. Throw an exception directly in the Controller class

throw new UserException(user.getUsername()+"No access rights");

4. Configure the global exception handler in the springMVC configuration file

   <bean class="cn.com.mvc.exception.UserExceptionResolver"></bean>

   

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324810007&siteId=291194637