当系统发生时, spring boot会自动处理异常, 这里通过自定义统一处理异常进行处理。
pom.xml文件创建一个IndexController类,定义一个正常方法和一个错误方法4.0.0 org.springframework.boot spring-boot-starter-parent 2.1.6.RELEASE com.huzh springboot-error 1.0-SNAPSHOT springboot-error springboot-error 1.8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-devtools runtime org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin
@RestController
public class IndexController {
@RequestMapping("/")
public String indesx() {
return "index";
}
@RequestMapping("/test")
public String test() {
Map map = null;
return map.toString();
}
}
访问项目,分析结果
-
访问http://localhost:8080/aa, 如下
-
访问http://localhost:8080/test, 如下
从上图可以看到,springboot报错的时候都在找/error这个地址,这时我们新建一个CommonErrorController来统一处理异常,这个类实现了ErrorController。
@RestController
public class CommonErrorController implements ErrorController {
private final String ERROR_PATH = "/error";
@Override
public String getErrorPath() {
return ERROR_PATH;
}
@RequestMapping(value = ERROR_PATH)
public String handleError() {
System.out.println(getErrorPath());
return "error";
}
}



