1、在 SpringMVC 的配置文件中配置 SimpleMappingExceptionResolver 進行全局的異常處理java
<!-- 全局異常配置 start 控制器異常處理--> <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="java.lang.Exception">errors/exceptionError</prop> <prop key="java.lang.Throwable">errors/throwableError</prop> </props> </property> <property name="statusCodes"> <props> <prop key="errors/500">500</prop> <prop key="errors/404">404</prop> <prop key="errors/400">400</prop> </props> </property> <!-- 設置日誌輸出級別,不定義則默認不輸出警告等錯誤日誌信息 --> <property name="warnLogCategory" value="WARN"></property> <!-- 默認錯誤頁面,當找不到上面mappings中指定的異常對應視圖時,使用本默認配置 --> <property name="defaultErrorView" value="errors/error"></property> <!-- 默認HTTP狀態碼 --> <property name="defaultStatusCode" value="500"></property> </bean> <!-- 全局異常配置 end -->
2、使用 ExceptionHandlerExceptionResolverweb
ExceptionHandlerExceptionResolver 主要處理類和方法中使用 @ControllAdvise 和 @ExceptionHandler(ArithmeticException.class) 註解定義的方法。spring
一、在 SpringMVC 配置文件中 添加 <mvc:annotation-driven/> 配置,該配置會自動註冊三個 Bean,分別是 DefaultHandlerExceptionResolver
ResponseStatusExceptionResolver、ExceptionHandlerExceptionResolver。 mvc
二、建立普通的JavaBean,在類上添加 @ControllAdvise 註解,在處理異常的方法上添加 @ExceptionHandler(ArithmeticException.class) 註解。app
package com.springmvc.handlers; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView; @ControllerAdvice public class MyExceptionHandler { @ExceptionHandler(ArithmeticException.class) public ModelAndView handleArithmeticException(Exception e){ ModelAndView mv = new ModelAndView("error"); mv.addObject("exception", e); System.out.println("出異常了:" + e); return mv; } }
若是在類上不添加 @ControllerAdvice 註解,只是用 @ExceptionHandler 註解修飾異常處理方法,則該異常處理方法只能處理本類中的異常,不能全局使用。spa
/**
* 1. 在 @ExceptionHandler 方法的入參中能夠加入 Exception 類型的參數, 該參數即對應發生的異常對象
* 2. @ExceptionHandler 方法的入參中不能傳入 Map. 若但願把異常信息傳導頁面上, 須要使用 ModelAndView 做爲返回值
* 3. @ExceptionHandler 方法標記的異常有優先級的問題.
* 4. @ControllerAdvice: 若是在當前 Handler 中找不到 @ExceptionHandler 方法來出來當前方法出現的異常,
* 則將去 @ControllerAdvice 標記的類中查找 @ExceptionHandler 標記的方法來處理異常.
*/日誌