springboot异常处理
Posted 第十八使徒
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
}
}
以上是关于springboot异常处理的主要内容,如果未能解决你的问题,请参考以下文章
SpringBoot启动报错“Consider defining a bean of type ‘xxx.mapper.UserMapper‘ in your configuration.“(代码片段
Springboot集成Common模块中的的全局异常处理遇见的问题
SpringBoot学习13:springboot异常处理方式3(使用@ControllerAdvice+@ExceptionHandle注解)