新建一个类 在class注解上@ControllerAdvice, 在方法上注解上@ExceptionHandler(value = Exception.class)
import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import javax.servlet.http.HttpServletRequest; /** * Created by LM on 2017/8/6. */ @ControllerAdvice(basePackages = "demo1.e1")//basePackages 拦截指定包的异常 public class GlobalDefaultExceptionHandler { @ExceptionHandler(value = Exception.class) public void defaultErrorHandler(HttpServletRequest req, Exception e) { //打印异常信息: e.printStackTrace(); System.out.println("GlobalDefaultExceptionHandler.defaultErrorHandler()"); } } package demo1.e1; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * Created by LM on 2017/8/6. */ @Controller @RequestMapping public class aa { @RequestMapping("/zeroException") public int zeroException(){ return 100/0; } @RequestMapping("/") public String hello(){ return "Hello world!"; } }