异常怎么处理?撸主很久之前的项目都是在 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("数据库中已存在该记录");
}
}
自定义异常
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;
}
}
页面响应
public class Result extends HashMap演示{ 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 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 了!!!
参考https://blog.52itstyle.vip/archives/5069/



