In Spring 3.2, the @ControllerAdvice annotation was added, which can be used to define @ExceptionHandler, @initBinder, @ModelAttribute, and applied to all @requestMapping. @ControllerAdvice Official documentation. Create global exception handling classes: Define uniform exception handling classes by using @ControllerAdvice, rather than individually in each Controller. The @ExceptionHandler is used to define the type of Exception the function is targeting, and finally maps the Exception object and request URL to error.html.

V Create a new exception catching class

Unified Exception Handling

package com.demo.common;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by toutou on 2018/12/9.
 */
@ControllerAdvice
public class CatchGlobalException {
    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.setViewName("error");
        return mav;
    }

}
Copy the code

verror page

Create error. HTML in the Templates directory and print the requested URL and message for the Exception object.

<! DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" > <head lang="en"> <meta Charset =" utF-8 "/> <title> sorry, this is an error page </title> </head> <body> <div> ﹃ _ ﹃ 〣 < / div > < div th: text = "${url}" > < / div > < div th: text = "${exception. Message}" > < / div > < / body > < / HTML >Copy the code

Effect of v

“Create” an exception in Controller.

    @RequestMapping("/debug")
    public String Debug(){
        int number = 5 / 0;
        return null;
    }
Copy the code

The running effect is as follows:

V Source code address

Github.com/toutouge/ja…

About the author: Focus on basic platform project development. If you have any questions or suggestions, please feel free to comment! Copyright notice: The copyright of this article belongs to the author and the blog garden, welcome to reprint, but without the consent of the author must retain this statement, and give the original text link in a prominent place on the page of the article. For the record: all comments and messages will be answered as soon as possible. You are welcome to correct your mistakes and make progress together. Or direct private message I support the blogger: if you think the article is helpful to you, you can click on the lower right corner of the article [recommendation]. Your encouragement is the author to adhere to the original and continuous writing of the biggest power! \