在springboot项目,报错有着默认的提示,这篇文章介绍一下如何统一处理异常。
新建项目,pom文件如下:
4.0.0 com.dalaoyang springboot_error0.0.1-SNAPSHOT jar springboot_error springboot_error org.springframework.boot spring-boot-starter-parent1.5.9.RELEASE UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starter-weborg.springframework.boot spring-boot-devtoolsruntime org.springframework.boot spring-boot-starter-testtest org.springframework.boot spring-boot-maven-plugin
创建一个IndexController,里面写两个方法,index方法正常跳转,test方法是故意写的一个nullpoint的错误的方法。 代码如下:
package com.dalaoyang.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
public class IndexController {
@RequestMapping("/")
public String index(){
return "index";
}
@RequestMapping("/test")
public String test(){
Map map = null;
return map.toString();
}
}启动项目访问http://localhost:8080/,如下图,没有任何问题
然后随便访问一个项目里没有的地址,比如http://localhost:8080/aaa,如下图所示,404没有找到:
访问http://localhost:8080/test,如下图500错误:
从图上可以看到,springboot报错的时候都在找/error这个地址,这时我们新建一个CommonErrorController来统一处理异常,这个类实现了ErrorController,代码如下:
package com.dalaoyang.Controller;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@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";
}
}重启项目,在访问http://localhost:8080/aaa和http://localhost:8080/test就都返回“error”字符串了,如下:
源码下载 :大老杨码云



