天天看點

SpringMVC 全局異常處理,傳回json

1.在spring-mvc.xml中增加配置:

比如我的freemarker視圖定義的是:/WEB-INF/template

我的頁面則放在template下的common目錄下,是以下方定義的是common/500,檔案擴充名根據視圖定義可以忽略

<mvc:annotation-driven />
	
	<!--全局異常輸出 -->
    <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="java.lang.Exception">common/500</prop>
            </props>
        </property>
        <property name="statusCodes">
            <props>
                <prop key="common/500">500</prop>
            </props>
        </property>
        <!-- 設定日志輸出級别,不定義則預設不輸出警告等錯誤日志資訊 -->
        <property name="warnLogCategory" value="WARN"></property>
        <!-- 預設錯誤頁面,當找不到上面mappings中指定的異常對應視圖時,使用本預設配置 -->
        <property name="defaultErrorView" value="common/500"></property>
        <!-- 預設HTTP狀态碼 -->
        <property name="defaultStatusCode" value="500"></property>
    </bean>
           

2.配置界面傳回

根據自己的頁面視圖,在對應目錄下增加檔案,這裡我采用的是freemarker,傳回标準的json串

"code": 500,
"msg": "系統異常,請聯系管理者",
"data": {
	<#assign errs=Request["exception"].getStackTrace()![]>
	<#list errs as err>
		<#assign className=Request["exception"].getStackTrace()[err_index].getClassName()!"">
		<#if className?contains("Controller") || className?contains("Service")>
			"Exception Type":"${Request["exception"].getClass()}",
			"Class Path":"${Request["exception"].getStackTrace()[err_index].getClassName()!""}",
			"Class Name":"${Request["exception"].getStackTrace()[err_index].getFileName()!""}",
			"Error Line":"${Request["exception"].getStackTrace()[err_index].getLineNumber()!""}",
			"Method Name":"${Request["exception"].getStackTrace()[err_index].getMethodName()!""}",
			"-----------------------------------------------------------------------",
			<br/>
		</#if>
	</#list>
 }
}
	
           

3.效果圖

{
    "code": 500,
    "msg": "系統異常,請聯系管理者",
    "data": {
        "Exception Type": "class java.lang.NullPointerException",
        "Class Path": "com.aliyun.web.user.UserController",
        "Class Name": "UserController.java",
        "Error Line": "57",
        "Method Name": "queryList",
        "-----------------------------------------------------------------------",
    }
}
           

版權聲明:本文為CSDN部落客「weixin_34319817」的原創文章,遵循CC 4.0 BY-SA版權協定,轉載請附上原文出處連結及本聲明。

原文連結:https://blog.csdn.net/weixin_34319817/article/details/91943662