springboot常用功能(四)统一异常处理并返回json格式数据
springboot提供,两个注解用做异常处理
1.@ControllerAdvice
2.@RestControllerAdvice
二者区别就在于 @ResponseBody ; @ControllerAdvice默认返回的是视图,加上@ResponseBody 返回为json格式数据
使用
@Slf4j
@RestControllerAdvice
public class HHExceptionHandler
{
/**
* 处理自定义异常
*/
@ExceptionHandler(HHException.class)
public R handleHWException(HHException e)
{
log.info("handleHHException");
R r = new R();
r.put("code", e.getCode());
r.put("msg", e.getMessage());
return r;
}
@ExceptionHandler(DuplicateKeyException.class)
public R handleDuplicateKeyException(DuplicateKeyException e)
{
log.info("handleDuplicateKeyException");
log.error(e.getMessage(), e);
return R.error("数据库中已存在该记录");
}
@ExceptionHandler(AuthorizationException.class)
public R handleAuthorizationException(AuthorizationException e)
{
log.error(e.getMessage(), e);
return R.error("没有权限,请联系管理员授权");
}
@ExceptionHandler(Exception.class)
public R defaultErrorHandler(Exception e)
{
log.info("handleException");
R r = new R();
if (e instanceof org.springframework.web.servlet.NoHandlerFoundException)
{
r.put("code", 404);
r.put("msg", "page not found");
} else
{
log.error(e.getMessage(), e);
r.put("code", 500);
r.put("msg", e.getMessage());
}
return r;
}
}
返回结果集R
public class R extends HashMap<String, Object>
{
private static final long serialVersionUID = 1L;
public R()
{
put("code", 200);
put("msg", "success");
}
public static R error()
{
return error(500, "未知异常,请联系管理员");
}
public static R error(String msg)
{
return error(500, msg);
}
public static R error(int code, String msg)
{
R r = new R();
r.put("code", code);
r.put("msg", msg);
return r;
}
public static R ok(String msg)
{
R r = new R();
r.put("msg", msg);
return r;
}
public static R ok(Map<String, Object> map)
{
R r = new R();
r.putAll(map);
return r;
}
public static R ok()
{
return new R();
}
public R put(String key, Object value)
{
super.put(key, value);
return this;
}
}