(4) Global exception capture for Springboot

Keywords: JSON Database

Original address: http://te-amo.site/user/article/info/ARTICLE20180223085118171

Written in the front

Exceptions are inevitable in project development, so it is important for an application to capture and handle exceptions uniformly in the project. It is easy for developers to find the cause of errors, and users can get a better experience of the server's timely response in case of errors.

1, Exception capture before logical business processing

Most of these exceptions are resource request errors, such as 404 exceptions caused by wrong url addresses.
To handle this exception, the ErrorController interface needs to be implemented. The code is as follows:

@Controller
public class ResourceExceptionHandler implements ErrorController {
    private static Logger logger = Logger.getLogger(ResourceExceptionHandler.class.getName());
    @Override
    public String getErrorPath() {
        return "/error";
    }
    /**
    *Handle exceptions that need to be returned and html pages
    **/
    @RequestMapping(value = "/error",produces = "text/html")
    public ModelAndView errorHtml(HttpServletResponse resp, HttpServletRequest req) {
        logger.info("page not found");
        return new ModelAndView("404.html");
    }
    /**
    *Handle exceptions that need to return JSON data
    **/
    @RequestMapping(value = "/error")
    @ResponseBody
    public Object error(HttpServletResponse resp, HttpServletRequest req) {
        logger.info("ResponseBody not found");
        return "ResourceExceptionHandler ResponseBody";
    }
}

2, Exception capture during @ RequestMapping

This kind of exception mainly includes parameter mismatch, parameter conversion and other exceptions
Use @ ControllerAdvice and inherit ResponseEntityExceptionHandler to handle this exception as follows:

@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {


    /**
     * Parameter shortage exception
     * Here's just one way
     * If you need to handle other exceptions, you can check the source code of the ResponseEntityExceptionHandler, and override the exception handling methods you need
     */
    @Override
    protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {

        return new ResponseEntity<Object>(ex.getMessage(), status);
    }
}

3, Exception capture in logical business processing

Exceptions in logical business processing mainly refer to various problems that may occur when processing business logic, such as null pointer, database error, etc.

(1) Application of rendering with Html template

This kind of application exception handling needs to implement the HandlerExceptionResolver interface

@Component
public class ModelAndViewExceptionHandler implements HandlerExceptionResolver {
    private static Logger logger = Logger.getLogger(ModelAndViewExceptionHandler.class.getName());
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        logger.info("ModelAndView abnormal");
        return new ModelAndView("error.html");
    }
}
(2)restful style application

Use @ ControllerAdvice and @ ExceptionHandler annotation to handle exceptions of this application

@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Object exceptionHandler(HttpServletRequest request, Exception e) throws Exception {
        logger.info("Exception handling logic");
        return "error";
    }
}

Posted by davey10101 on Tue, 31 Mar 2020 17:57:03 -0700