springboot异常处理

1.使用@ControllerAdvice注解
public class GlobalException {
//设置拦截的异常
   // @ExceptionHandler(value = {java.lang.NullPointerException.class,java.lang.ArithmeticException.class})
    public ModelAndView nullPointExceptionHandler(Exception e){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("err",e.toString());
        modelAndView.setViewName("error1");
        return modelAndView;
    }
}

2.SimpleMappingExceptionResolver对异常和异常页面进行对应

package com.mc_74120.springbootexceptionandjunit.exception;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import java.util.Properties;

//@Configuration
public class GlobalException2 {
    @Bean
    public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver(){
        SimpleMappingExceptionResolver simpleMappingExceptionResolver=new SimpleMappingExceptionResolver();
        Properties properties=new Properties();
        properties.put("java.lang.NullPointerException","error");
        properties.put("java.lang.ArithmeticException","error1");
        simpleMappingExceptionResolver.setExceptionMappings(properties);
        return  simpleMappingExceptionResolver;
    }
}

3.实现HandlerExceptionResolver接口

package com.mc_74120.springbootexceptionandjunit.exception;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;

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

@Configuration
public class GlobalException3 implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        ModelAndView modelAndView=new ModelAndView();
        //根据异常的不同 跳转到不同的页面
        if(e instanceof  NullPointerException){
          modelAndView.setViewName("error");
        }
        if (e instanceof  ArithmeticException){
            modelAndView.setViewName("error1");
        }
        return modelAndView;
    }
}

 

posted @ 2020-04-21 12:07  第十八使徒  阅读(131)  评论(0)    收藏  举报