前言
异常怎么处理?撸主很久之前的项目都是在 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 了!!!
关注我,后续更多干货奉上!
本文系本站编辑转载,文章版权归原作者所有,内容为作者个人观点,转载目的在于传递更多信息,并不代表本站赞同其观点和对其真实性负责。如涉及作品内容、版权和其它问题,请与本站联系,本站将在第一时间删除内容!