SpringBoot入门--全局异常捕获

Web页面跳转形式

自定义异常处理
CustomExceptionHandler.java

@ControllerAdvice
public class CustomExceptionHandler {

    public static final String CUSTOM_ERROR_VIEW = "error";

	@ExceptionHandler(value = Exception.class)
    public Object errorHandler(HttpServletRequest reqest,
    		HttpServletResponse response, Exception e) throws Exception {

    	e.printStackTrace();

		ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", reqest.getRequestURL());
        mav.setViewName(CUSTOM_ERROR_VIEW);
        return mav;
    }
}
@Controller
@RequestMapping("err")
public class ErrorController {

	@RequestMapping("/error")
	public String error() {
		
		int a = 1 / 0;
		
		return "thymeleaf/error";
	}
}

error.html
在这里插入图片描述

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title>捕获全局异常</title>
</head>
<body>
    <h1 style="color: red">发生错误:</h1>
    <div th:text="${url}"></div>
    <div th:text="${exception.message}"></div>
</body>
</html>

结果:
在这里插入图片描述

Ajax形式

AjaxExceptionHandler.java

@RestControllerAdvice
public class AjaxExceptionHandler {

	@ExceptionHandler(value = Exception.class)
	public JSONResult defaultErrorHandler(HttpServletRequest req,
										  Exception e) throws Exception {

		e.printStackTrace();
		return JSONResult.errorException(e.getMessage());
	}
}
	@RequestMapping("/ajaxerror")
	public String ajaxerror() {
		
		return "thymeleaf/ajaxerror";
	}
	@RequestMapping("/getAjaxerror")
	@ResponseBody
	public JSONResult getAjaxerror() {
		
		int a = 1 / 0;
		
		return JSONResult.ok();
	}

在这里插入图片描述
ajaxerror.html调用ajaxerror.js

<!DOCTYPE html >
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
    
    <script th:src="@{/static/js/jquery.min.js}"></script>
    
</head>
<body>

<h1>测试ajax错误异常</h1>

<script th:src="@{/static/js/ajaxerror.js}"></script>
</body>
</html>

ajaxerror.js
在这里插入图片描述

$.ajax({
    	url: "/err/getAjaxerror",
    	type: "POST",
    	async: false,
    	success: function(data) {
    		debugger;
            if(data.status == 200 && data.msg == "OK") {
            	alert("success");
            } else {
            	alert("发生异常:" + data.msg);
            }
    	},
        error: function (response, ajaxOptions, thrownError) {
        	debugger;
        	alert("error");       
        }
    });

在这里插入图片描述
在这里插入图片描述

兼容Web和Ajax

只留这个CustomExceptionHandler.java,AjaxExceptionHandler.java不用
在这里插入图片描述

@ControllerAdvice
public class CustomExceptionHandler {

    public static final String CUSTOM_ERROR_VIEW = "error";

//	@ExceptionHandler(value = Exception.class)
//    public Object errorHandler(HttpServletRequest reqest,
//    		HttpServletResponse response, Exception e) throws Exception {
//
//    	e.printStackTrace();
//
//		ModelAndView mav = new ModelAndView();
//        mav.addObject("exception", e);
//        mav.addObject("url", reqest.getRequestURL());
//        mav.setViewName(CUSTOM_ERROR_VIEW);
//        return mav;
//    }

    @ExceptionHandler(value = Exception.class)
    public Object errorHandler(HttpServletRequest reqest,
                               HttpServletResponse response, Exception e) throws Exception {

        e.printStackTrace();

        if (isAjax(reqest)) {
            return JSONResult.errorException(e.getMessage());
        } else {
            ModelAndView mav = new ModelAndView();
            mav.addObject("exception", e);
            mav.addObject("url", reqest.getRequestURL());
            mav.setViewName(CUSTOM_ERROR_VIEW);
            return mav;
        }
    }

    /* @description : 判断是否是ajax请求
     * 
     * @param httpRequest
     * @return : 
     * @author cdw
     * @date 2020/10/10 15:51
     */
    public static boolean isAjax(HttpServletRequest httpRequest) {
        return (httpRequest.getHeader("X-Requested-With") != null
                && "XMLHttpRequest"
                .equals(httpRequest.getHeader("X-Requested-With").toString()));
    }
}

访问http://localhost:8080/err/ajaxerror
在这里插入图片描述
在这里插入图片描述
访问http://localhost:8080/err/error
在这里插入图片描述
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值