springmvc custom exception handler (2)

Ideas:

        Parse out the exception type
        If the exception type is a system-defined exception, directly extract the exception information and display it on the error page
        If the exception type is not a system-defined exception, construct a custom exception type (the information is "unknown error")


step one

public class CustomExceptionResolver implements HandlerExceptionResolver {

    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) {
        ex.printStackTrace();
        GyException gyException = null;

        //If a system-defined exception is thrown, it will be converted directly
        if(ex instanceof GyException) {
            gyException = (GyException) ex;
        } else {
            //If the exception thrown is not a system-defined exception, reconstruct an unknown error exception
            //Here I also have CustomException to save trouble, in fact, a new exception should be defined
            gyException = new GyException("System unknown error");
        }
       // return error message to foreground
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("message", gyException.getMessage());
        modelAndView.setViewName("custom_error");

        return modelAndView;
    }

}

Step 2: Register the global exception handler in the springmvc configuration file

  <bean class="com.test.validator.controller.exception.CustomExceptionResolver"></bean>

Step 3 throws an exception

public String ecxeption(HttpServletRequest httpServletRequest , HttpServletResponse httpServletResponse ,User user) throws Exception {
	    if(user.getUserName()==null) {
	    	System.out.println("Username cannot be empty");
				 throw new GyException("Username cannot be empty");
	    	
	    }
	    return "custom_error";
    }

Step 4: Take out the wrong data on the page

${message}


Guess you like

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