码迷,mamicode.com
首页 > 编程语言 > 详细

springboot异常处理

时间:2020-04-21 13:20:37      阅读:61      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!