SpringBoot第四章: 处理全局异常

 

我们在springmvc中有讲过处理全局异常,当然,springboot也是有全局异常处理的。

一. 自定义 处理常见的404和 505 页面。

例如,我们输入了一个程序中不存在的路径,那么会跳转到404找不到的界面。

输入: http://localhost:8080/j/show1

其实,springboot中还自带有自定义处理404.html和500.html异常。

只需要在resources/templates目录下放入error.html就可以进行页面自定义跳转,

但前提是需要有前章的渲染模板开启,要么是thymeleaf模板。

 

如果想精准定位到404.html或者505html的状态码,那么需要在resources/templates下再新建一个error文件包,放入404.html和500.html

 

二. 重写 自定义异常处理 :BasicErrorController

我们可以去继承 BasicErrorController 类, 去重写方法 。 来 定制自己需要的404页面

ErrorPageController.java :

其中,errorMap 中有5个属性:

timestamp:时间戳

status : 状态 404

error :错误 not found

message: 信息 no message

path :  路径 错误路径

package com.SpringBoot.demo.error;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.boot.web.servlet.error.ErrorAttributes;

public class ErrorPageController extends BasicErrorController {

	public ErrorPageController(ErrorAttributes errorAttributes, ErrorProperties errorProperties,
			List<ErrorViewResolver> errorViewResolvers) {
		super(errorAttributes, errorProperties, errorViewResolvers);
		// TODO Auto-generated constructor stub
	}

	@Override
	protected Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {
		// TODO Auto-generated method stub
		Map<String, Object> errorMap = super.getErrorAttributes(request, includeStackTrace);
		errorMap.remove("message");
		errorMap.remove("path");
		return errorMap;
	}
	
	

}

重写之后,我们需要去配置下,就是替换spring中的全局异常处理功能。

ErrorConfiguration.java:

package com.springboot.demo.SpringBootDemoProject.error;

import java.util.List;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ErrorConfiguration {

	@Bean
	public ErrorPageController basicErrorController(ErrorAttributes errorAttributes, 
			ServerProperties serverProperties, 
			ObjectProvider<List<ErrorViewResolver>> errorViewResolversProvider) {
		return new ErrorPageController(errorAttributes, serverProperties.getError(), 
				errorViewResolversProvider.getIfAvailable());
	}
}
 

 

三. 在springmvc中经常使用的 例外异常处理: @ControllerAdvice + @ExceptionHandler

比如,你想处理空指针、找不到类等异常:

MyExceptionHandler.java:  使用注解配置下 NullPointerException 异常

package com.SpringBoot.demo.error;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class MyExceptionHandler {
	@ExceptionHandler
	public ModelAndView exp(Exception ex) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("errorInfo", ex.getMessage());
		
		if(ex instanceof NullPointerException) {
			modelAndView.setViewName("error/error_null");
		}else {
			modelAndView.setViewName("error/error_other");
		}
		
		return modelAndView;
	}

}

跳转页面:

error_null.jsp:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>error_null title here</title>
</head>
<body>
<h1>error_null . NullPointerException</h1>

</body>
</html>

error_other.jsp:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>error_null . NullPointerException</h1>
</body>
</html>

 

空指针异常测试控制层:

package com.SpringBoot.demo.error;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("e")
public class ErrorTestController {
	@RequestMapping("show")
	public String show(ModelMap model) {
		
		 String str = null;
		 str.charAt(0);
		 
		//String[] str = {"22", "33"}; String ss = str[2];
		
		return "thymeleaf";
	}
}

测试结果:

总结,只需要这么一个文件,就会对整个项目的所有NullPointerException 异常进行捕获拦截,跳转到自己定义的异常页面

 

当然,像这种 @ControllerAdvice + @ExceptionHandler的方式,也能分开跳转页面:

@ExceptionHandler(NullPointerException.class)  指定例外异常即可,其他异常会跳转到未指定的异常中

package com.SpringBoot.demo.error;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class MyExceptionHandler {
	/*@ExceptionHandler
	public ModelAndView exp(Exception ex) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("errorInfo", ex.getMessage());
		
		if(ex instanceof NullPointerException) {
			modelAndView.setViewName("error/error_null");
		}else {
			modelAndView.setViewName("error/error_other");
		}
		
		return modelAndView;
	}*/
	
	@ExceptionHandler(NullPointerException.class)
	public ModelAndView exp(Exception ex) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("errorInfo", ex.getMessage());
		modelAndView.setViewName("error/error_null");	
		return modelAndView;
	}
	
	@ExceptionHandler
	public ModelAndView exp1(Exception ex) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("errorInfo", ex.getMessage());
		modelAndView.setViewName("error/error_other");	
		return modelAndView;
	}
}

 

四. SimpleMappingExceptionResolver全局异常处理

MySimpleMappingExceptionResolver.java :

此类也为一个配置类,需要使用@Configuration进行配置到spring容器中, 使用的类是SimpleMappingExceptionResolver 

Properties : 配置文件,用于保存异常信息和异常界面

package com.SpringBoot.demo.error;

import java.util.Properties;

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

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

 

我们还是通过:

ErrorTestController.java进行测试

package com.SpringBoot.demo.error;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("e")
public class ErrorTestController {
	@RequestMapping("show")
	public String show(ModelMap model) {
		
		 String str = null;
		 str.charAt(0);
		 
		//String[] str = {"22", "33"}; String ss = str[2];
		
		return "thymeleaf";
	}
}

测试过程中需要把其他的配置文件屏蔽。测试成功跳转到了nullpointerException.

 

五. 实现mvc中的  HandlerExceptionResolver 处理器

通过实现:HandlerExceptionResolver接口 ,去重写resolveException方法

package com.SpringBoot.demo.error;

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

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

@Configuration
public class MyHandlerExceptionResolver implements HandlerExceptionResolver {

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		// TODO Auto-generated method stub
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("errorInfo", ex.getMessage());
		
		if(ex instanceof NullPointerException) {
			modelAndView.setViewName("error/error_null");
		}else {
			modelAndView.setViewName("error/error_other");
		}
		return modelAndView;
	}

}

实现效果一样

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

逼哥很疯狂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值