springboot全局异常的处理@ControllerAdvice和@ExceptionHandler

在项目中,我们经常遇到程序运行异常,也经常根据业务需要自定义异常,springboot给我们提供了一种便利的方式捕获全局异常,解决访问url地址不友好提示的问题。

@RequestMapping("/error")
    public void error() throws HbkException {
        try {
            int a = 5/0;
        }catch (Exception e){
            throw new HbkException("程序运行错误");
        }
    }

如上在程序运行时会报错。我自定义了一个异常叫HbkException(直接继承Exception即可,并提供一个调用父类的构造函数即可)

package com.hbk.springbootmail.advice;

import com.hbk.springbootmail.exception.HbkException;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

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

@ControllerAdvice
public class HbkExceptionHandler {
    private String errorPage = "error";// 自定义当程序报HbkException异常跳转的页面
    @ExceptionHandler(value = HbkException.class)
    public Object handler(HttpServletRequest request, HttpServletResponse response,Exception e){
        System.out.println(e.getMessage());
        ModelAndView map = new ModelAndView();
        map.addObject("msg", e.getMessage());
        map.addObject("url", request.getRequestURL());
        map.setViewName(errorPage);
        return map;
    }
}

@ControllerAdvice和@ExceptionHandler这两个注解非常强大,具体可以查看源码。其中@ExceptionHandler的value为我们捕获的具体异常,在这里我们只是跳转到error.html页面,使用ModelAndView对象即可。

在error.html进行自定义显示。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>测试页面</title>
</head>
<body>
<h3>error 页面</h3>
    <span th:text="${msg}"></span><br>
    <span th:text="${url}"></span>
</body>
</html>

在这里插入图片描述

发布了1184 篇原创文章 · 获赞 272 · 访问量 203万+

猜你喜欢

转载自blog.csdn.net/huangbaokang/article/details/104059374