springboot异常处理

2021-02-10 10:16

阅读:563

标签:contex   put   ppi   turn   使用   Servle   spring   control   framework   

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异常处理

标签:contex   put   ppi   turn   使用   Servle   spring   control   framework   

原文地址:https://www.cnblogs.com/mc-74120/p/12743645.html


评论


亲,登录后才可以留言!