本文共 3076 字,大约阅读时间需要 10 分钟。
在springboot项目,报错有着默认的提示,这篇文章介绍一下如何统一处理异常。
新建项目,pom文件如下:
4.0.0 com.dalaoyang springboot_error 0.0.1-SNAPSHOT jar springboot_error springboot_error org.springframework.boot spring-boot-starter-parent 1.5.9.RELEASE UTF-8 UTF-8 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
创建一个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;/** * @author dalaoyang * @Description * @project springboot_learn * @package com.dalaoyang.Controller * @email yangyang@dalaoyang.cn * @date 2018/4/28 */@RestControllerpublic class IndexController { @RequestMapping("/") public String index(){ return "index"; } @RequestMapping("/test") public String test(){ Map map = null; return map.toString(); }}
启动项目访问,如下图,没有任何问题
然后随便访问一个项目里没有的地址,比如,如下图所示,404没有找到:
访问,如下图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;/** * @author dalaoyang * @Description * @project springboot_learn * @package com.dalaoyang.Controller * @email yangyang@dalaoyang.cn * @date 2018/4/28 */@RestControllerpublic 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"; }}
重启项目,在访问和就都返回"error"字符串了,如下:
源码下载 :
个人网站:
转载地址:http://uliao.baihongyu.com/