本文为大家分享了spring boot全局异常处理,供大家参考,具体内容如下
1、后台处理异常
a、引入thymeleaf依赖
<!-- thymeleaf模板插件 --> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-thymeleaf</artifactid> </dependency>
b、在application.properties文件中设置属性
#关闭thymeleaf模板的缓存 spring.thymeleaf.cache=false
c、编写后台处理handler
import org.springframework.web.bind.annotation.controlleradvice; import org.springframework.web.bind.annotation.exceptionhandler; @controlleradvice public class globalexceptionhandler { //设置此handler处理所有异常 @exceptionhandler(value=exception.class) public void defaulterrorhandler(){ system.out.println("-------------default error"); } }
d、后台异常打印
-------------default error
2017-06-16 14:54:05.314 warn 6892 --- [nio-8080-exec-1] .m.m.a.exceptionhandlerexceptionresolver : resolved exception caused by handler execution: org.springframework.dao.incorrectresultsizedataaccessexception: result returns more than one elements; nested exception is javax.persistence.nonuniqueresultexception: result returns more than one elements
2、页面处理异常
a、编写html模板页面
<!doctype html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <meta charset="utf-8" /> <title>insert title here</title> </head> <body> <h1 th:inlines="text">异常出现啦</h1> ${messages} </body> </html>
b、修改handler
import org.springframework.web.bind.annotation.controlleradvice; import org.springframework.web.bind.annotation.exceptionhandler; import org.springframework.web.bind.annotation.responsebody; @controlleradvice public class globalexceptionhandler { @exceptionhandler(value=exception.class) @responsebody public string defaulterrorhandler(){ system.out.println("-------------default error"); return "系统错误,请联系管理员"; } }
c、页面访问结果
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问, 点击进行留言回复!!
详解SpringBoot修改启动端口server.port的四种方式
网友评论