cef异常处理_SpringBoot异常处理

该博客介绍了如何在Spring Boot应用中配置全局异常处理类,包括处理普通异常和自定义异常。通过`@RestControllerAdvice`注解定义异常处理器,返回JSON数据或跳转到自定义错误页面。自定义异常类`MyException`继承自`RuntimeException`,并提供了状态码和错误信息。同时,展示了如何创建并引用Thymeleaf模板作为错误页面。
摘要由CSDN通过智能技术生成

1. 配置全局异常和自定义异常

异常处理类(包括全局和自定义)

@RestControllerAdvice

public class CustomExtHandler {

/**

* 处理全局异常

* 返回json数据,由前端去判断加载什么页面(推荐)

*/

@ExceptionHandler(value = Exception.class)

Object handleException(Exception e, HttpServletRequest request) {

log.error("url [{}], msg [{}]", request.getRequestURL(), e.getMessage());

Map map = new HashMap<>(3);

map.put("code", 500);

map.put("msg", e.getMessage());

map.put("url", request.getRequestURL());

return map;

}

/**

* 处理自定义异常

* 返回json数据,由前端去判断加载什么页面(推荐)

*/

@ExceptionHandler(value = MyException.class)

Object handleMyException(MyException e, HttpServletRequest request) {

log.error("url [{}], msg [{}]", request.getRequestURL(), e.getMessage());

Map map = new HashMap<>(3);

map.put("code", e.getCode());

map.put("msg", e.getMsg());

map.put("url", request.getRequestURL());

return map;

}

}

自定义异常类

@Getter

@Setter

public class MyException extends RuntimeException {

//状态码

private String code;

//错误信息

private String msg;

public MyException(String code, String msg) {

this.code = code;

this.msg = msg;

}

}

2.返回自定义页面

创建自定义页面位置,位置如下图:

Error Page

1fb9cef5e227

error.html位置

引入thymeleaf依赖

org.springframework.boot

spring-boot-starter-thymeleaf

异常处理类

@RestControllerAdvice

public class CustomExtHandler {

/**

* 处理自定义异常

* 进行页面跳转

*/

@ExceptionHandler(value = MyException.class)

Object handleMyException(MyException e, HttpServletRequest request) {

ModelAndView modelAndView = new ModelAndView();

modelAndView.setViewName("error.html");

modelAndView.addObject("msg", e.getMessage());

return modelAndView;

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值