Spring Boot全局異常處理解析
本文為大家分享了Spring Boot全局異常處理,供大家參考,具體內(nèi)容如下
1、后臺處理異常
a、引入thymeleaf依賴
<!-- thymeleaf模板插件 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
b、在application.properties文件中設置屬性
#關(guān)閉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">異常出現(xiàn)啦</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 "系統(tǒng)錯誤,請聯(lián)系管理員";
}
}
c、頁面訪問結(jié)果

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Spring 事務事件監(jiān)控及實現(xiàn)原理解析
本文首先會使用實例進行講解Spring事務事件是如何使用的,然后會講解這種使用方式的實現(xiàn)原理。感興趣的朋友跟隨小編一起看看吧2018-09-09
spring boot + mybatis如何實現(xiàn)數(shù)據(jù)庫的讀寫分離
這篇文章主要給大家介紹了關(guān)于spring boot + mybatis如何實現(xiàn)數(shù)據(jù)庫的讀寫分離的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用spring boot具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧2019-09-09
C#使用MySQLConnectorNet和MySQLDriverCS操作MySQL的方法
這篇文章主要介紹了C#使用MySQLConnectorNet和MySQLDriverCS操作MySQL的方法,相比普通方法能夠在Windows下簡化很多操作步驟,需要的朋友可以參考下2016-04-04
SpringBoot框架實現(xiàn)支付和轉(zhuǎn)賬功能
在 Spring Boot 框架中實現(xiàn)支付和轉(zhuǎn)賬功能時,涉及到多個細節(jié)和注意點,這些功能通常需要高度的安全性、穩(wěn)定性和可擴展性,本文介紹了實現(xiàn)支付和轉(zhuǎn)賬功能的一些關(guān)鍵點,需要的朋友可以參考下2024-08-08

