Spring Boot异常处理

自定义错误页面

        SpringBoot默认的处理异常的机制:SpringBoot 默认的已经提供了一套处理异常的机制。一旦程序中出现了异常 SpringBoot 会向/error 的 url 发送请求。在 springBoot 中提供了一个叫 BasicErrorController 来处理/error 请求,然后跳转到默认显示异常的页面来展示异常信息。

如 果我 们 需 要 将 所 有 的 异 常 同 一 跳 转 到 自 定 义 的 错 误 页 面 , 需 要 再src/main/resources/

templates 目录下创建 error.html 页面。注意:名称必须叫 error

controller

/**
 * SpringBoot处理异常方式一:自定义错误页面
 */
@Controller
public class DemoController {
	
	@RequestMapping("/show")
	public String showInfo(){
		String str = null;
		str.length();
		return "index";
	}
	
	@RequestMapping("/show2")
	public String showInfo2(){
		int a = 10/0;
		return "index";
	}
}

 

错误页面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>错误提示页面</title>
</head>
<body>
	出错了,请与管理员联系。。。
	<span th:text="${error}"></span>
</body>
</html>

整合web访问全局异常处理器

处理思路

 

创建全局异常处理器

/**
 * 通过实现HandlerExceptionResolver接口做全局异常处理
 */
@Component
public class GlobleException implements HandlerExceptionResolver {


    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        if (e instanceof ArithmeticException) {
            modelAndView.setViewName("error1");
        } else if (e instanceof NullPointerException) {
            modelAndView.setViewName("error2");
        }
            modelAndView.addObject("error", e.toString());
        return modelAndView;
    }
}

 

错误页面

error1.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>错误提示页面-ArithmeticException</title>
</head>
<body>
	出错了,请与管理员联系。。。
	<span th:text="${error}"></span>
</body>
</html>

   

error2.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>错误提示页面-NullPointerException</title>
</head>
<body>
	出错了,请与管理员联系。。。
	<span th:text="${error}"></span>
</body>
</html>

整合ajax全局异常处理

创建全局异常处理器

@ControllerAdvice
public class AjaxGlobleException {
    @ResponseBody
    @ExceptionHandler
/**
     * 处理全局异常
     * @param exception   异常
     * @return Map<String, Object>
     */
    public Map errorHandler(Exception e) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("status", 500);
        map.put("msgs", e.toString());
        return map;
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

冰冰很社恐

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

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

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

打赏作者

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

抵扣说明:

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

余额充值