首先要保证启动类能够扫到异常处理类。
编写全局捕获异常处理类:
package wyh.error;
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
*
* <p>Title: GlobalException</p>
* <p>Description:全局捕获异常 异常返回1:json格式,2:返回页面 </p>
* @author wyh
* @date Dec 2, 2018
*/
@ControllerAdvice//(basePackages="wyh.controller")如果不写basePackages,默认是扫描到所有@Controller和@RestController//springboot的异常切入点,basePackages定义扫包范围,一般扫controller,当定义的那个包中发生了异常,就会执行这个类。
public class GlobalException {
@ExceptionHandler(RuntimeException.class)//拦截错误
@ResponseBody//返回json.如果是返回视图,就用ModelAndView
public Map<String, Object> errorResult(){
Map<String, Object> map = new HashMap<String, Object>();
map.put("errorCode", "500");
map.put("errorMsg", "系统错误");
return map;
}
}
编写异常:
package wyh.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ErrorController {
@RequestMapping("/getUser")
public String getUser(int i) {//参数在访问路径后面直接用?连接
int j = 1/i;
return "success"+j;
}
}
目录结构:
启动测试:
此时出现异常时,控制台就不会抛出异常了。