1.添加异常类
package myshop.config; import javax.servlet.http.HttpServletRequest; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; /* * 1.新建一个class,这里取名为GlobalDefaultExceptionHandler * 2.在class上添加注解,@ControllerAdvice * 3.在class中添加一个方法 * 4.在方法上添加@ExcetionHandler拦截相应的异常 * 5.如果返回的是View -- 方法返回值是ModelAndView * 6.如果返回的是String或者是Json数据,那么需要在方法上添加@RequestBody注解 */ @ControllerAdvice public class GlobalDefaultExceptionHandler { @ExceptionHandler(Exception.class) @ResponseBody public String defaultExceptionHandler(HttpServletRequest req, Exception e) { //ModelAndView mv = new ModelAndView(); //mv.setViewName(""); return "对不起,服务器繁忙..."; } }
2.添加启动类
package myshop; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class App { public static void main(String[] args) { // TODO Auto-generated method stub SpringApplication.run(App.class, args); } }