SpringBoot2.2.x(十四)统一异常处理

本系列文章都是基于SpringBoot2.2.5.RELEASE

自定义异常类

public class HtmlException extends Exception {
    public HtmlException(String message) {
        super(message);
    }
}

public class JsonException extends Exception {
    public JsonException(String message) {
        super(message);
    }
}

编写Controller

@Controller
public class HelloController {
    @GetMapping("/hello/{type}")
    public String hello(@PathVariable String type) throws Exception {
        if ("1".equals(type)) {
            throw new HtmlException("抛出异常,返回HTML页面");
        } else if ("2".equals(type)) {
            throw new JsonException("抛出异常,返回JSON页面");
        }
        return "hello";
    }
}

统一异常处理

创建全局异常处理类:通过使用@ControllerAdvice定义统一的异常处理类。

@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 捕获HtmlException,统一返回错误的HTML页面
     */
    @ExceptionHandler(value = HtmlException.class)
    public ModelAndView htmlErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.addObject("message", e.getMessage());
        mav.addObject("url", req.getRequestURL());
        mav.setViewName("error");
        return mav;
    }
    /**
     * 捕获JsonException,统一返回JSON数据
     */
    @ExceptionHandler(value = JsonException.class)
    @ResponseBody
    public Object jsonErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        Map<String, Object> result = new HashMap<>();
        result.put("code","error");
        result.put("message",e.getMessage());
        return result;
    }
}

error.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>统一异常处理</title>
</head>
<body>
<h1 style="text-align: center">统一异常处理</h1>
<div th:text="${url}"></div>
<div th:text="${message}"></div>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值