1. 程式人生 > >SpringMVC全局異常處理

SpringMVC全局異常處理

img print stack final 郵件 控制臺 用戶體驗 code 測試

問題描述:當最外層Controller向外拋出異常,會導致頁面直接顯示異常信息,造成不友好的用戶體驗

處理思路:

技術分享圖片

一、配置log4j

● 導入log4j和slf4j的依賴:slf4f是所有日誌處理的的規範,推薦用slf4j操作(導入org.slf4j)

<!-- 日誌處理 -->
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version> </dependency>

● 將log4j.properties文件放入resources目錄

log4j.rootLogger=INFO,A3,STDOUT

log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
log4j.appender.STDOUT.layout.ConversionPattern
=[%p] [%l] %10.10c - %m%n log4j.appender.A3=org.apache.log4j.RollingFileAppender log4j.appender.A3.file=logs/server.log log4j.appender.A3.MaxFileSize=1024KB log4j.appender.A3.MaxBackupIndex=10 log4j.appender.A3.layout=org.apache.log4j.PatternLayout log4j.appender.A3.layout.ConversionPattern=\n\n[%-5p] %d{yyyy-MM-dd HH\:mm\:ss,SSS} method\:%l%n%m%n

二、繼承HandlerExceptionResolver來處理異常

package cn.e3mall.search.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GlobalExceptionResolver implements HandlerExceptionResolver {
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest,
                                         HttpServletResponse httpServletResponse, Object o, Exception e) {
        //打印控制臺
        e.printStackTrace();
        
        //寫日誌
        LOGGER.error("系統發生異常",e);
        
        //發郵件通知開發人員debug
        //TODO
        
        //顯示錯誤頁面
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error/exception");
        return modelAndView;
    }
}

三、在springmvc配置全局異常處理器

<!--配置全局異常處理器-->
    <bean class="cn.e3mall.search.exception.GlobalExceptionResolver"/>

四、測試異常處理

在Controller加入如下代碼

int i = 1/0;

搜索結果展示錯誤頁面exception.jsp

[ERROR] 2019-01-20 17:18:38,634 method:cn.e3mall.search.exception.GlobalExceptionResolver.resolveException(GlobalExceptionResolver.java:21)
系統發生異常
java.lang.ArithmeticException: / by zero

SpringMVC全局異常處理