前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot 2.x 开发案例之优雅的处理异常

SpringBoot 2.x 开发案例之优雅的处理异常

作者头像
小柒2012
发布2020-01-08 10:25:16
4470
发布2020-01-08 10:25:16
举报
文章被收录于专栏:IT笔记IT笔记

前言

异常怎么处理?撸主很久之前的项目都是在 Controller 层一个个 try 的,之后也曾自己写过AOP实现异常拦截处理。不过,这里给小伙伴推荐一款统一处理异常神器。

代码案例

微服务、前后端分离的时代,应该很少有小伙伴使用模板了吧,大多都是返回Json数据。墙裂推荐大家使用 @RestControllerAdvice,可以用于定义@ExceptionHandler@InitBinder@ModelAttribute,并应用到所有@RequestMapping中。

异常处理器
代码语言:javascript
复制
/**
 *  异常处理器
 */
@RestControllerAdvice
public class RrExceptionHandler {
    
    private Logger logger = LoggerFactory.getLogger(getClass());

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e){
        logger.error(e.getMessage(), e);
        return Result.error();
    }
    
    /**
     * 自定义异常
     */
    @ExceptionHandler(RrException.class)
    public Result handleRRException(RrException e){
        Result r = new Result();
        r.put("code", e.getCode());
        r.put("msg", e.getMessage());
        return r;
    }
    @ExceptionHandler(DuplicateKeyException.class)
    public Result handleDuplicateKeyException(DuplicateKeyException e){
        logger.error(e.getMessage(), e);
        return Result.error("数据库中已存在该记录");
    }
}
自定义异常
代码语言:javascript
复制
/**
 *  自定义异常
 *  创建者  爪洼笔记
 *  博客 https://blog.52itstyle.vip
 *  创建时间    2019年8月15日
 */
public class RrException extends RuntimeException {
    
    private static final long serialVersionUID = 1L;
    
    private String msg;
    
    private int code = 500;
    
    public RrException(String msg) {
        super(msg);
        this.msg = msg;
    }
    
    public RrException(String msg, Throwable e) {
        super(msg, e);
        this.msg = msg;
    }
    
    public RrException(String msg, int code) {
        super(msg);
        this.msg = msg;
        this.code = code;
    }
    
    public RrException(String msg, int code, Throwable e) {
        super(msg, e);
        this.msg = msg;
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }
}
页面响应
代码语言:javascript
复制
/**
 *  页面响应
 *  @Author  小柒2012
 *  @Date     2019年1月21日
 */
public class Result extends HashMap<String, Object> {

    private static final long serialVersionUID = 1L;

    public Result() {
        put("code", 0);
    }

    public static Result error() {
        return error(500, "未知异常,请联系管理员");
    }

    public static Result error(String msg) {
        return error(500, msg);
    }

    public static Result error(int code, String msg) {
        Result r = new Result();
        r.put("code", code);
        r.put("msg", msg);
        return r;
    }

    public static Result ok(Object msg) {
        Result r = new Result();
        r.put("msg", msg);
        return r;
    }

    public static Result ok(Map<String, Object> map) {
        Result r = new Result();
        r.putAll(map);
        return r;
    }

    public static Result ok() {
        return new Result();
    }

    @Override
    public Result put(String key, Object value) {
        super.put(key, value);
        return this;
    }
}

演示

我们尝试模拟一个经典异常:

代码语言:javascript
复制
@RequestMapping("eatChicken")
public Result eatChicken() {
     String 马化腾 = null;
     if(马化腾.equals("码云")){
         System.out.println("一起搞基");
     }
     return Result.ok();
}

前台输出:

代码语言:javascript
复制
{"msg":"未知异常,请联系管理员","code":500}

后台打印:

代码语言:javascript
复制
java.lang.NullPointerException: null
    at com.itstyle.chicken.module.tools.web.ArticleController.get(ArticleController.java:35)

小结

是不是很爽,再也不用 try 了!!!

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-01-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

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

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 代码案例
    • 异常处理器
      • 自定义异常
        • 页面响应
        • 演示
        • 小结
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档