本文為大家分享了Spring Boot全局異常處理,供大家參考,具體內(nèi)容如下
1、后臺(tái)處理異常
a、引入thymeleaf依賴
1
2
3
4
5
|
<!-- thymeleaf模板插件 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> |
b、在application.properties文件中設(shè)置屬性
1
2
|
#關(guān)閉thymeleaf模板的緩存 spring.thymeleaf.cache= false |
c、編寫后臺(tái)處理Handler
1
2
3
4
5
6
7
8
9
10
11
12
|
import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class GlobalExceptionHandler { //設(shè)置此handler處理所有異常 @ExceptionHandler (value=Exception. class ) public void defaultErrorHandler(){ System.out.println( "-------------default error" ); } } |
d、后臺(tái)異常打印
-------------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模板頁面
1
2
3
4
5
6
7
8
9
10
11
12
|
<!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" >異常出現(xiàn)啦</ h1 > ${messages} </ body > </ html > |
b、修改Handler
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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 "系統(tǒng)錯(cuò)誤,請(qǐng)聯(lián)系管理員" ; } } |
c、頁面訪問結(jié)果
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。