为了账号安全,请及时绑定邮箱和手机立即绑定

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

标签:
Java SpringBoot

前言

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

代码案例

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

异常处理器

/**
 *  异常处理器
 */
@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("数据库中已存在该记录");
	}
}

自定义异常

/**
 *  自定义异常
 *  创建者  爪洼笔记
 *  博客 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;
	}
}

页面响应

/**
 *  页面响应
 *  @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;
	}
}

演示

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

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

前台输出:

{"msg":"未知异常,请联系管理员","code":500}

后台打印:

java.lang.NullPointerException: null
	at com.itstyle.chicken.module.tools.web.ArticleController.get(ArticleController.java:35)
	

小结

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

参考

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
JAVA开发工程师
手记
粉丝
1.7万
获赞与收藏
2434

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消