SpringBoot配置全局的异常捕获 - web页面跳转

请结合springboot学习教程项目github地址 https://github.com/heng1234/spring-boot_one来理解

ErrorController

/**
	 * 不是ajax形式访问
	 * @return
	 */
	@RequestMapping("err")
	public String error() {
		
		int res = 1 / 0;
		return "/error/error";
	}

定义个异常捕捉类:

package com.yh.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.yh.pojo.HlvyJSONResult;

@ControllerAdvice
public class HlvyExceptionHandler {
	
	 static final  String TO_URL = "/thymeleaf/error/error";

	 /**
	  * 捕获不是ajax请求
	  * @param request
	  * @param response
	  * @param e
	  * @return
	  * @throws Exception
	  */
/*	 @ExceptionHandler(value= Exception.class)
	 public Object errExceyion(HttpServletRequest request,HttpServletResponse response,Exception e) throws Exception {
		e.printStackTrace();
		 ModelAndView view = new ModelAndView();
		 System.out.println("this HlvyExceptionHandler");
		 view.addObject("e", e);
		 view.addObject("url", request.getRequestURI());
		 view.setViewName(TO_URL);
		 return view;
		 
	 }*/
	
}


错误页面:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2 th:text="${e}"></h2>
<h2 th:text="${url}"></h2>
</body>
</html>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值