7. SpringMVC custom exception class

7. SpringMVC custom exception class

1. The idea of ​​exception handling

In java, there are generally two ways to handle exceptions:

  • A method to capture processing (try-catch) in the current method, this processing method will cause the coupling of business code and exception handling code.

  • The other is to not handle it yourself, but throw it to the caller to handle (throws), and the caller is throwing it to its caller, that is, throwing up. Based on this method, the exception handling mechanism of SpringMVC is derived.

The system's dao, service, and controller are all thrown upward through throws Exception, and finally the springmvc front-end controller is handed over to the exception handler for exception handling, as shown below:

image-20220312170306527

2. Custom exception handler

Step analysis:

  1. Create an exception handler class to implement handlerExceptionResolver
  2. Configure exception handler
  3. Write exception pages
  4. Test exception jump

(1) Create an exception handler class to implement handlerExceptionResolver

public class GlobalExeceptionResovler implements HandlerExceptionResolver {
    
    
    /**
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o:对应的处理器
     * @param e;实际抛出的异常对象
     * @return
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
    
    
        ModelAndView model = new ModelAndView();
        //具体的异常处理 产生异常后,跳转到一个最终的异常页面
        model.addObject("error",e.getMessage());//得到错误信息
        model.setViewName("error");
        return model;
    }
}

(2) Configure the exception handler in the Spring configuration file

<!--    定义错误异常页面-->
    <bean id="globalExecptionResovler" class="com.weihong.excption.GlobalExeceptionResovler"/>
    

(3) Write an exception page

<html>
<head>
    <title>Title</title>
</head>
<body>
  <h2>这是一个错误页面</h2>
  <h5>错误信息为:${error}</h5>
</body>
</html>

(4) Test exception jump

    @RequestMapping("/jumpErrorPage")
    public String jumpErrorPage(){
    
    
        int res = 10 / 0;
        return "success";
    }

( 5) Test results

image-20220312170744238

3. Web exception handling mechanism

  • When the request status is 404 or 500, the specified page jumps.

  • In its web.xml configuration is as follows:

<!--处理500异常-->
<error-page>
  <error-code>500</error-code>
  <location>/500.jsp</location>
</error-page>
<!--处理404异常-->
<error-page>
  <error-code>404</error-code>
  <location>/404.jsp</location>
</error-page>

Guess you like

Origin blog.csdn.net/qq_41239465/article/details/123473986