Spring MVC異常統一處理的三種方式

2021-10-10 01:29:33 字數 2682 閱讀 4980

spring 統一異常處理有 3 種方式,分別為:

使用 @ exceptionhandler 註解

實現 handlerexceptionresolver 介面

使用 @controlleradvice 註解

使用該註解有乙個不好的地方就是:進行異常處理的方法必須與出錯的方法在同乙個controller裡面。使用如下:

@controller      

public class globalcontroller )

public string exception(myexception e)

public void test()

}

可以看到,這種方式最大的缺陷就是不能全域性控制異常。每個類都要寫一遍。

這種方式可以進行全域性的異常控制。例如:

@component  

public class exceptiontest implements handlerexceptionresolver

}

上文說到 @ exceptionhandler 需要進行異常處理的方法必須與出錯的方法在同乙個controller裡面。那麼當**加入了 @controlleradvice,則不需要必須在同乙個 controller 中了。這也是 spring 3.2 帶來的新特性。從名字上可以看出大體意思是控制器增強。 也就是說,@controlleradvice + @ exceptionhandler 也可以實現全域性的異常捕捉。

請確保此webexceptionhandle 類能被掃瞄到並裝載進 spring 容器中。

logger.error("服務執行異常", e);

e.printstacktrace();

return serviceresponsehandle.failed("server_error");

}}如果 @exceptionhandler 註解中未宣告要處理的異常型別,則預設為引數列表中的異常型別。所以還可以寫成這樣:

@controlleradvice

public class globalexceptionhandler

}

引數物件就是 controller 層丟擲的異常物件!

繼承 responseentityexceptionhandler 類來實現針對 rest 介面 的全域性異常捕獲,並且可以返回自定義格式:

@slf4j

@controlleradvice

public class exceptionhandlerbean extends responseentityexceptionhandler )

public responseentityhandledatanotfoundexception(runtimeexception ex, webrequest request) throws ioexception

/*** 根據各種異常構建 responseentity 實體. 服務於以上各種異常

* @param ex

* @param request

* @param specificexception

* @return

*/private responseentitygetresponseentity(runtimeexception ex, webrequest request, returnstatuscode specificexception)

}

以上就是 spring 處理程式統一異常的三種方式。

SpringMVC異常統一處理

正文 spring 統一異常處理有 3 種方式,分別為 使用 exceptionhandler 註解 實現 handlerexceptionresolver 介面 使用 controlleradvice 註解 package com.tao.smp.exception api統一的返回結果類 pub...

springmvc異常統一處理(一)

目錄 正文 spring 統一異常處理有 3 種方式,分別為 使用 exceptionhandler 註解 實現 handlerexceptionresolver 介面 使用 controlleradvice 註解 使用該註解有乙個不好的地方就是 進行異常處理的方法必須與出錯的方法在同乙個contr...

SpringMVC 全域性異常統一處理

使用 exceptionhandler 註解 實現 handlerexceptionresolver 介面 使用 controlleradvice 註解 當以上三個方式,一起出現時,只執行執行範圍最小的方式,後面的方式不再執行處理 執行範圍 exceptionhandler controllerad...