欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot @ExceptionHandler與@ControllerAdvice異常處理詳解

 更新時(shí)間:2022年10月28日 10:13:57   作者:showswoller  
在Spring Boot應(yīng)用的開發(fā)中,不管是對(duì)底層數(shù)據(jù)庫操作,對(duì)業(yè)務(wù)層操作,還是對(duì)控制層操作,都會(huì)不可避免的遇到各種可預(yù)知的,不可預(yù)知的異常需要處理,如果每個(gè)處理過程都單獨(dú)處理異常,那么系統(tǒng)的代碼耦合度會(huì)很高,工作量大且不好統(tǒng)一,以后維護(hù)的工作量也很大

前言

如果能將所有類型的異常處理從各層中解耦出來,則既保證了相關(guān)處理過程的功能較單一,也實(shí)現(xiàn)了異常信息的統(tǒng)一處理和維護(hù)。幸運(yùn)的是,Spring框架支持這樣的實(shí)現(xiàn)。接下來將從自定義error頁面。@ExceptionHandler注解以及@ControllerAdvice3種方式講解Spring Boot應(yīng)用的異常統(tǒng)一處理

具體處理步驟如下:

自定義error頁面

在Spring Boot Web應(yīng)用的src/main/resources/templates 目錄下添加error.html頁面 訪問發(fā)生錯(cuò)誤或異常時(shí),Spring Boot將自動(dòng)找到該頁面作為錯(cuò)誤頁面。Spring Boot為錯(cuò)誤頁面提供了以下屬性

  • timestamp 錯(cuò)誤發(fā)生時(shí)間
  • status HTTP狀態(tài)碼
  • error 錯(cuò)誤原因
  • exception 異常的類名
  • message 異常消息
  • errors BindingResult異常里的各種錯(cuò)誤
  • trace 異常跟蹤信息
  • path 錯(cuò)誤發(fā)生時(shí)請(qǐng)求的URL路徑

1: 創(chuàng)建名為com.ch.ch5_3.exception的包 并在該包中創(chuàng)建名為MyException 具體代碼如下

package com.ch.ch5_3.exception;
public class MyException extends Exception {
	private static final long serialVersionUID = 1L;
	public MyException() {
		super();
	}
	public MyException(String message) {
		super(message);
	}
}

2:創(chuàng)建控制器類TestHandleExceptionController

創(chuàng)建名為com.ch,ch5_3.controller的包 并在該包中創(chuàng)建名為TestHandleExceptionController的控制器類,在該控制器類中,在4個(gè)請(qǐng)求處理方法,一個(gè)是導(dǎo)航到index.html 另外三個(gè)分別拋出不同的異常 部分代碼如下

package com.ch.ch5_3.controller;
import java.sql.SQLException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
    public void db() throws SQLException { 
        throw new SQLException("數(shù)據(jù)庫異常");
    }  
	@RequestMapping("/my")  
    public void my() throws MyException {  
        throw new MyException("自定義異常");
    }
	@RequestMapping("/no")  
    public void no() throws Exception {  
        throw new Exception("未知異常");
    } 
}

3:View視圖頁面

Thymeleaf模板默認(rèn)將視圖頁面放在src/main/resources/templates目錄下。因此我們?cè)趕rc/main/resources/templates 目錄下新建html頁面文件,index.html和error.html

在index.html頁面中 有4個(gè)超鏈接請(qǐng)求,3個(gè)請(qǐng)求在控制器中有對(duì)應(yīng)處理,另一個(gè)請(qǐng)求是404錯(cuò)誤

部分代碼如下

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>index</title>
<link rel="stylesheet" th:href="@{css/bootstrap.min.css}" rel="external nofollow"  rel="external nofollow"  />
<!-- 默認(rèn)訪問 src/main/resources/static下的css文件夾-->
<link rel="stylesheet" th:href="@{css/bootstrap-theme.min.css}" rel="external nofollow"  rel="external nofollow"  />
				<a th:href="@{db}" rel="external nofollow" >處理數(shù)據(jù)庫異常</a><br>
				<a th:href="@{my}" rel="external nofollow" >處理自定義異常</a><br>
				<a th:href="@{no}" rel="external nofollow" >處理未知錯(cuò)誤</a>
				<hr>
				<a th:href="@{nofound}" rel="external nofollow" >404錯(cuò)誤</a>
			</div>
		</div>
	</div>
</body>
</html>

error.html頁面部分代碼如下

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>error</title>
<link rel="stylesheet" th:href="@{css/bootstrap.min.css}" rel="external nofollow"  rel="external nofollow"  />
<!-- 默認(rèn)訪問 src/main/resources/static下的css文件夾-->
<link rel="stylesheet" th:href="@{css/bootstrap-theme.min.css}" rel="external nofollow"  rel="external nofollow"  />
</head>
<body>
            <div class="common-hint-word">
                <div th:text="${#dates.format(timestamp,'yyyy-MM-dd HH:mm:ss')}"></div>
                <div th:text="${message}"></div>
                <div th:text="${error}"></div>
            </div>
        </div>
    </div>
</body>
</html>

@ExceptionHandler注解

上面自定義頁面并沒有處理異常,可以使用@ExceptionHandler注解處理異常,如果有一個(gè)由該注解修飾的方法,那么當(dāng)任何方法拋出異常時(shí)都由它來處理

添加一個(gè)注解修飾的方法 具體代碼如下

@ExceptionHandler(value=Excetption.class)
public String handlerException(Exception e){
if(e istanceof SQLException){
return "sql error";
}
else if(e instanceof MYException){
return"myError";
}
else{
return "noerror";
}
}

@ControllerAdvice注解

使用它注解的類時(shí)當(dāng)前Spring Boot應(yīng)用中所有類的統(tǒng)一異常處理類,該類中使用@ExceptionHandler注解的方法統(tǒng)一處理異常,不需要在每個(gè)Controller中逐一定義異常處理方法,這是因?yàn)閷?duì)所有注解了@ControllerAdvice注解進(jìn)行全局異常處理

創(chuàng)建GlobalExceptionHandlerController的類 具體代碼如下

package com.ch.ch5_3.controller;
import java.sql.SQLException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import com.ch.ch5_3.exception.MyException;
@ControllerAdvice
public class GlobalExceptionHandlerController {
	@ExceptionHandler(value=Exception.class)
	public String handlerException(Exception e) {
		//數(shù)據(jù)庫異常
		if (e instanceof SQLException) {
			return "sqlError";
		} else if (e instanceof MyException) {//自定義異常
			return "myError";
		} else {//未知異常
			return "noError";
		}
	}
}

到此這篇關(guān)于SpringBoot @ExceptionHandler與@ControllerAdvice異常處理詳解的文章就介紹到這了,更多相關(guān)SpringBoot @ExceptionHandler與@ControllerAdvice內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • java?List集合去除null的4種方法

    java?List集合去除null的4種方法

    這篇文章主要給大家介紹了java?List集合去除null的3種方法,文中通過代碼示例將每種方法都介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Java具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-09-09
  • Java比較器實(shí)現(xiàn)方法項(xiàng)目案例

    Java比較器實(shí)現(xiàn)方法項(xiàng)目案例

    這篇文章主要介紹了Java比較器實(shí)現(xiàn)方法,結(jié)合具體項(xiàng)目案例形式分析了Java比較器相關(guān)排序操作技巧,需要的朋友可以參考下
    2019-03-03
  • Java中CyclicBarrier的用法分析

    Java中CyclicBarrier的用法分析

    CyclicBarrier和CountDownLatch一樣,都是關(guān)于線程的計(jì)數(shù)器。用法略有不同,測(cè)試代碼如下:
    2013-03-03
  • 為什么ConcurrentHashMap的key value不能為null,map可以?

    為什么ConcurrentHashMap的key value不能為null,map可以?

    這篇文章主要介紹了為什么ConcurrentHashMap的key value不能為null,map可以呢?具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2021-01-01
  • java比較器Comparable接口與Comaprator接口的深入分析

    java比較器Comparable接口與Comaprator接口的深入分析

    本篇文章是對(duì)java比較器Comparable接口與Comaprator接口進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
    2013-06-06
  • java8的stream如何取max

    java8的stream如何取max

    這篇文章主要介紹了java8的stream如何取max問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • mybatis 多表關(guān)聯(lián)mapper文件寫法操作

    mybatis 多表關(guān)聯(lián)mapper文件寫法操作

    這篇文章主要介紹了mybatis 多表關(guān)聯(lián)mapper文件寫法操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-12-12
  • 如何用Eureka + Feign搭建分布式微服務(wù)

    如何用Eureka + Feign搭建分布式微服務(wù)

    Eureka是Spring Cloud Netflix的一部分,是一個(gè)服務(wù)注冊(cè)中心。其服務(wù)生態(tài)中主要有三個(gè)角色:Eureka注冊(cè)中心、服務(wù)提供者、服務(wù)消費(fèi)者。服務(wù)提供者注冊(cè)到Eureka后,服務(wù)消費(fèi)者就能夠直接向Eureka查詢當(dāng)前有哪些服務(wù)可用,再從中選取一個(gè)消費(fèi).本文講解如何搭建分布式微服務(wù)
    2021-06-06
  • Java Kafka 消費(fèi)積壓監(jiān)控的示例代碼

    Java Kafka 消費(fèi)積壓監(jiān)控的示例代碼

    這篇文章主要介紹了Java Kafka 消費(fèi)積壓監(jiān)控,本文通過示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-07-07
  • 使用Java通過OAuth協(xié)議驗(yàn)證發(fā)送微博的教程

    使用Java通過OAuth協(xié)議驗(yàn)證發(fā)送微博的教程

    這篇文章主要介紹了使用Java通過OAuth協(xié)議驗(yàn)證發(fā)送微博的教程,使用到了新浪微博為Java開放的API weibo4j,需要的朋友可以參考下
    2016-02-02

最新評(píng)論