SpringBoot: 14.異常處理方式4(使用SimpleMappingExceptionResolver處理異常)(轉)

 

修改異常處理方法3中的全局異常處理Controller便可html

複製代碼
package bjsxt.exception;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import java.util.Properties;

/**
 * Created by Administrator on 2019/2/14.
 * 全局異常處理類,使用SimpleMappingExceptionResolver 作全局異常處理
 * 優勢:直接在一個方法裏對須要處理的異常跳轉不一樣的視圖,比較簡單方便
 * 缺點:沒法把錯誤信息傳遞到視圖層
 */

@Configuration
public class GlobalException {

    /**
     *
     * @return
     */
    @Bean
    public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver(){
        SimpleMappingExceptionResolver resolver=new SimpleMappingExceptionResolver();
        Properties properties=new Properties();
        /**
         * 參數一:異常的類型,注意必須是異常類型的全名
         * 參數二:視圖名稱
         */
        properties.put("java.lang.ArithmeticException","error_arithmetic");
        properties.put("java.lang.NullPointerException","error_nullPointer");
        resolver.setExceptionMappings(properties);
        return resolver;
    }

}
相關文章
相關標籤/搜索