前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >springboot全局异常处理

springboot全局异常处理

原创
作者头像
无敌小菜鸟
修改2022-02-20 12:49:49
9970
修改2022-02-20 12:49:49
举报
文章被收录于专栏:搬砖笔记搬砖笔记

优化了下项目的异常处理,直接上代码!

全局处理器

代码语言:javascript
复制
/**
 * 全局异常处理器
 * @author xx
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    public Map<String, Object> exceptionHandler(Exception e) {
        log.info("捕获全局异常:" + e.getMessage());
        log.info(e.toString());
        Map<String, Object> res = new HashMap<>();
        res.put("code", 5001);
        res.put("message", e.getMessage());
        //res.put("cause",e.getCause().toString());
        res.put("stackTrace[0]",e.getStackTrace()[0]);
        return res;
    }
}

异常类

代码语言:javascript
复制
/**
 * 自定义异常
 * @author xx
 */
public class CustomException extends RuntimeException {
    private static final long serialVersionUID = 1L;

    private Integer code;

    private String message;

    public CustomException(String message) {
        this.message = message;
    }

    public CustomException(Integer code) {
        this.code = code;
    }

    public CustomException(String message, Integer code) {
        this.message = message;
        this.code = code;
    }

    public CustomException(Integer code, String message, Throwable e) {
        this.code = code;
        this.message = message;
        this.code = code;
    }

    public CustomException(Integer code,String message) {
        Map<String,Object> res = new HashMap<>();
        this.code = code;
        this.message = message;
    }


    public CustomException(String message, Throwable e) {
        super(message, e);
        this.message = message;
    }

    @Override
    public String getMessage() {
        return message;
    }

    public Integer getCode() {
        return code;
    }
}

测试自定义异常

代码语言:javascript
复制
@RestController
public class TestController {


    @GetMapping("test")
    public String test() {
        if (true) {
            throw new CustomException("1111");
        }
        //int a = 1/0;
        return "hello";
    }
}

页面输出样式

1
1

测试代码异常

代码语言:javascript
复制
@RestController
public class TestController {


    @GetMapping("test")
    public String test() {
        //if (true) {
        //    throw new CustomException("1111");
        //}
        int a = 1/0;
        return "hello";
    }
}

页面输出样式

2
2

以上基本满足项目需要,暂时先这样处理。

腾云先锋(TDP,Tencent Cloud Developer Pioneer)是腾讯云GTS官方组建并运营的技术开发者群体。这里有最专业的开发者&客户,能与产品人员亲密接触,专有的问题&需求反馈渠道,有一群志同道合的兄弟姐妹。来加入属于我们开发者的社群吧!

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 全局处理器
  • 异常类
  • 测试自定义异常
    • 页面输出样式
    • 测试代码异常
      • 页面输出样式
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档