SSM project adds exception handling function

SSM project adds exception handling function

table of Contents

1. Exception handling through the status code returned by the request

1.1. First need to be configured in web.xml

1.2. Add jsp file in the specified location

1.3. Verification

2. The overall exception capture mechanism

2.1. Implement SpringMVC's HandlerExceptionResolver

2.2. Verification


1. Exception handling through the status code returned by the request

Please refer to the specific status code.

https://blog.csdn.net/fmyzc/article/details/78048074

(Note: Sorry to quote directly without my consent.)

I only dealt with the 404 exception information here, which can be added according to the actual situation of the project.

1.1. First need to be configured in web.xml

<!--异常页面,当没有发现的时候,会根基这个404代码返回相对应的jsp页面 -->
<error-page>
  <error-code>404</error-code>
  <location>/WEB-INF/jsp/error/404.jsp</location>
</error-page>

 

 

 Note: The status code information returned by all browsers can be configured here, and different status code information can be jumped to different jsp files.

1.2. Add jsp file in the specified location

 

1.3. Verification

 Start the service, enter a URL that is not configured in the program, and return to the corresponding page.

 

2. The overall exception capture mechanism

2.1. Implement SpringMVC's HandlerExceptionResolver

Before introducing the overall exception capture mechanism, we need to implement SpringMVC's HandlerExceptionResolver interface.

package edu.wan.handler;

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

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

@Component
public class MyHandlerExceptionResolver  implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        String errorMessage = null;
        //首先可以对异常进行判断
        if (e instanceof NullPointerException){
            errorMessage = "咋回事,大兄弟,你咋还空指针了呢";
        }
        //返回错误页面
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("errorMessage",errorMessage);
        modelAndView.setViewName("error");
        return modelAndView;
    }
}

 

2.2. Verification

I modified the code of my Controller layer for verification.

public @ResponseBody User findUserById(){
    int id = 1;
    userService = null;
    return userService.findById(id);
}

After starting the service and calling the specified Controller, it will jump to the exception handling layer. According to different exception information, we assemble different data packages to the front end, and let the front end process the data.

 

 

Guess you like

Origin blog.csdn.net/baidu_31572291/article/details/114978531