SpringBoot學習15:springboot異常處理方式5(經過實現HandlerExceptionResolver類)

修改異常處理方式4中的全局異常處理controllerjava

package com.bjsxt.exception;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Properties;

/**
 * Created by Administrator on 2019/2/14.
 * 全局異常處理類,經過實現 HandlerExceptionResolver類作全局異常處理
 * 優勢:相對於方法4能夠傳遞異常信息
 */

@Configuration
public class GlobalException implements HandlerExceptionResolver{


    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest,
           HttpServletResponse httpServletResponse, @Nullable Object o, Exception e) {

        ModelAndView mv = new ModelAndView();
        //判斷不一樣異常類型,作不一樣視圖跳轉
        if(e instanceof ArithmeticException){
            mv.setViewName("error_arithmetic");
        }
        if(e instanceof NullPointerException){
            mv.setViewName("error_nullPointer");
        }
        mv.addObject("msg", e.toString());
        return mv;
    }
}
相關文章
相關標籤/搜索