完善WeixinException

This commit is contained in:
jinyu 2016-05-05 23:22:13 +08:00
parent ce653e049d
commit aff76298d3
15 changed files with 1822 additions and 416 deletions

View File

@ -1,6 +1,7 @@
package com.foxinmy.weixin4j.exception; package com.foxinmy.weixin4j.exception;
import com.foxinmy.weixin4j.util.StringUtil; import com.foxinmy.weixin4j.util.StringUtil;
import com.foxinmy.weixin4j.util.WeixinErrorUtil;
/** /**
* 调用微信接口抛出的异常 * 调用微信接口抛出的异常
@ -15,17 +16,17 @@ public class WeixinException extends Exception {
private static final long serialVersionUID = 7148145661883468514L; private static final long serialVersionUID = 7148145661883468514L;
private String errorCode; private String code;
private String errorMsg; private String desc;
public WeixinException(String errorCode, String errorMsg) { public WeixinException(String code, String desc) {
this.errorCode = errorCode; this.code = code;
this.errorMsg = errorMsg; this.desc = desc;
} }
public WeixinException(String errorMsg) { public WeixinException(String desc) {
this.errorCode = "-1"; this.code = "-1";
this.errorMsg = errorMsg; this.desc = desc;
} }
public WeixinException(Throwable e) { public WeixinException(Throwable e) {
@ -37,25 +38,27 @@ public class WeixinException extends Exception {
} }
public String getErrorCode() { public String getErrorCode() {
return errorCode; return code;
} }
public String getErrorMsg() { public String getErrorMsg() {
return errorMsg; return desc;
} }
@Override @Override
public String getMessage() { public String getMessage() {
StringBuilder buf = new StringBuilder(); StringBuilder buf = new StringBuilder();
if (StringUtil.isNotBlank(errorCode)) { if (StringUtil.isNotBlank(code)) {
buf.append(errorCode); buf.append(code);
} }
if (StringUtil.isNotBlank(errorMsg)) { if (StringUtil.isNotBlank(desc)) {
buf.append(" ").append(errorMsg); buf.append(" >> ").append(desc);
} }
if (buf.length() == 0) { if (buf.length() > 0) {
buf.append(" >> ").append(WeixinErrorUtil.getText(code));
return buf.toString();
} else {
return super.getMessage(); return super.getMessage();
} }
return buf.toString();
} }
} }

View File

@ -12,14 +12,14 @@ package com.foxinmy.weixin4j.exception;
public class WeixinPayException extends WeixinException { public class WeixinPayException extends WeixinException {
private static final long serialVersionUID = 7148145661883468514L; private static final long serialVersionUID = 7148145661883468514L;
public WeixinPayException(String errorMsg) { public WeixinPayException(String desc) {
super(errorMsg); super(desc);
} }
public WeixinPayException(String errorCode, String errorMsg) { public WeixinPayException(String code, String desc) {
super(errorCode, errorMsg); super(code, desc);
} }
public WeixinPayException(Throwable e) { public WeixinPayException(Throwable e) {
super(e); super(e);
} }

View File

@ -22,8 +22,6 @@ import com.foxinmy.weixin4j.http.factory.HttpClientFactory;
import com.foxinmy.weixin4j.logging.InternalLogger; import com.foxinmy.weixin4j.logging.InternalLogger;
import com.foxinmy.weixin4j.logging.InternalLoggerFactory; import com.foxinmy.weixin4j.logging.InternalLoggerFactory;
import com.foxinmy.weixin4j.model.Consts; import com.foxinmy.weixin4j.model.Consts;
import com.foxinmy.weixin4j.util.StringUtil;
import com.foxinmy.weixin4j.util.WeixinErrorUtil;
import com.foxinmy.weixin4j.xml.XmlStream; import com.foxinmy.weixin4j.xml.XmlStream;
/** /**
@ -95,7 +93,8 @@ public class WeixinRequestExecutor {
return doRequest(request); return doRequest(request);
} }
protected WeixinResponse doRequest(HttpRequest request) throws WeixinException { protected WeixinResponse doRequest(HttpRequest request)
throws WeixinException {
request.setParams(params); request.setParams(params);
try { try {
logger.info("weixin request >> " + request.getMethod() + " " logger.info("weixin request >> " + request.getMethod() + " "
@ -144,10 +143,6 @@ public class WeixinRequestExecutor {
JsonResult jsonResult = response.getAsJsonResult(); JsonResult jsonResult = response.getAsJsonResult();
response.setJsonResult(true); response.setJsonResult(true);
if (jsonResult.getCode() != 0) { if (jsonResult.getCode() != 0) {
if (StringUtil.isBlank(jsonResult.getDesc())) {
jsonResult.setDesc(WeixinErrorUtil.getText(Integer
.toString(jsonResult.getCode())));
}
throw new WeixinException(Integer.toString(jsonResult.getCode()), throw new WeixinException(Integer.toString(jsonResult.getCode()),
jsonResult.getDesc()); jsonResult.getDesc());
} }

View File

@ -97,9 +97,11 @@ public class JSSDKConfigurator {
* *
* @param url * @param url
* 当前网页的URL不包含#及其后面部分 * 当前网页的URL不包含#及其后面部分
* @return * @return jssdk配置JSON字符串
* @see <a * @see <a
* href="http://mp.weixin.qq.com/wiki/11/74ad127cc054f6b80759c40f77ec03db.html#.E6.AD.A5.E9.AA.A4.E4.B8.89.EF.BC.9A.E9.80.9A.E8.BF.87config.E6.8E.A5.E5.8F.A3.E6.B3.A8.E5.85.A5.E6.9D.83.E9.99.90.E9.AA.8C.E8.AF.81.E9.85.8D.E7.BD.AE">通过config接口注入权限验证配置</a> * href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115&token=&lang=zh_CN">公众号JSSDK</a>
* @see <a
* href="http://qydev.weixin.qq.com/wiki/index.php?title=%E5%BE%AE%E4%BF%A1JS-SDK%E6%8E%A5%E5%8F%A3">企业号JSSDK</a>
* @throws WeixinException * @throws WeixinException
*/ */
public String toJSONConfig(String url) throws WeixinException { public String toJSONConfig(String url) throws WeixinException {

View File

@ -19,7 +19,7 @@ public abstract class AbstractTokenCreator implements TokenCreator {
} }
/** /**
* 缓存key:附加weixin4j前缀 * 缓存key:附加weixin4j_前缀
* *
* @return * @return
*/ */

View File

@ -16,9 +16,9 @@ import com.foxinmy.weixin4j.model.Token;
*/ */
public interface TokenStorager extends CacheStorager<Token> { public interface TokenStorager extends CacheStorager<Token> {
/** /**
* 考虑到程序的临界值,实际有效时间应该减去下面这个数 * 考虑到临界情况,在实际有效时间上减去60秒
*/ */
final long CUTMS = 1 * 60 * 1000l; final long CUTMS = 60 * 1000l;
/** /**
* 缓存key的前缀 * 缓存key的前缀
*/ */

View File

@ -74,11 +74,14 @@ public final class WeixinErrorUtil {
} }
public String getText() { public String getText() {
return StringUtil.isBlank(text) ? "未知错误" : text; return StringUtil.isBlank(text) ? "" : text;
} }
} }
public static String getText(String code) throws RuntimeException { public static String getText(String code) throws RuntimeException {
if (StringUtil.isBlank(code)) {
return "";
}
String text = errorCacheMap.get(code); String text = errorCacheMap.get(code);
if (StringUtil.isBlank(text)) { if (StringUtil.isBlank(text)) {
ErrorTextHandler textHandler = new ErrorTextHandler(code); ErrorTextHandler textHandler = new ErrorTextHandler(code);

View File

@ -36,16 +36,19 @@
</plugins> </plugins>
</build> </build>
<dependencies> <dependencies>
<!-- 微信公众平台 -->
<dependency> <dependency>
<groupId>com.foxinmy</groupId> <groupId>com.foxinmy</groupId>
<artifactId>weixin4j-mp</artifactId> <artifactId>weixin4j-mp</artifactId>
<version>1.6.8</version> <version>1.6.8</version>
</dependency> </dependency>
<!-- 微信企业号 -->
<dependency> <dependency>
<groupId>com.foxinmy</groupId> <groupId>com.foxinmy</groupId>
<artifactId>weixin4j-qy</artifactId> <artifactId>weixin4j-qy</artifactId>
<version>1.6.8</version> <version>1.6.8</version>
</dependency> </dependency>
<!-- 微信被动消息(回调模式) -->
<dependency> <dependency>
<groupId>com.foxinmy</groupId> <groupId>com.foxinmy</groupId>
<artifactId>weixin4j-server</artifactId> <artifactId>weixin4j-server</artifactId>
@ -63,5 +66,12 @@
<artifactId>spring-context</artifactId> <artifactId>spring-context</artifactId>
<version>4.2.1.RELEASE</version> <version>4.2.1.RELEASE</version>
</dependency> </dependency>
<!-- test.... -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.9.1</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -0,0 +1,36 @@
package com.foxinmy.weixin4j.test;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;
public class ErrorBuilder {
public static void main(String[] args) throws Exception {
Map<String, String> error = new TreeMap<String, String>();
error.putAll(QyErrorBuilder.build());
error.putAll(MpErrorBuilder.build());
StringBuilder xml = new StringBuilder();
xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
xml.append("<!-- 公众平台错误码:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433747234&token=&lang=zh_CN -->");
xml.append("<!-- 企业号错误码:http://qydev.weixin.qq.com/wiki/index.php?title=%E5%85%A8%E5%B1%80%E8%BF%94%E5%9B%9E%E7%A0%81%E8%AF%B4%E6%98%8E -->");
xml.append("<errors>");
for (Entry<String, String> entry : error.entrySet()) {
xml.append("<error>");
xml.append("<code>").append(entry.getKey()).append("</code>");
xml.append("<text>").append(entry.getValue()).append("</text>");
xml.append("</error>");
}
xml.append("<!-- 商户平台错误码 -->");
error = PayErrorBuilder.builder();
for (Entry<String, String> entry : error.entrySet()) {
xml.append("<error>");
xml.append("<code>").append(entry.getKey()).append("</code>");
xml.append("<text>").append(entry.getValue()).append("</text>");
xml.append("</error>");
}
xml.append("</errors>");
System.err.println("\n");
System.err.println(xml.toString());
}
}

View File

@ -0,0 +1,110 @@
package com.foxinmy.weixin4j.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import sun.org.mozilla.javascript.internal.NativeArray;
import sun.org.mozilla.javascript.internal.NativeObject;
/**
* 收集微信公众平台错误码
*
* @className MpErrorBuilder
* @author jy
* @date 2016年5月5日
* @since JDK 1.7
* @see
*/
public class MpErrorBuilder {
private static final String HOME = "https://mp.weixin.qq.com/wiki";
private static final String RESOURCE = "https://mp.weixin.qq.com/wiki?action=doc&id=%s";
private static List<String> collectUrl() throws Exception {
Document root = Jsoup.connect(HOME).get();
List<String> resources = null;
Elements eles = root.getElementById("resMenu").getElementsByTag("a");
if (eles.isEmpty()) {
Element ele = root.getElementsByTag("script").last();
StringBuilder script = new StringBuilder();
script.append("window = {};");
script.append("seajs = {};");
script.append("seajs.use = function(arg1,arg2){return window.cgiData.list};");
script.append("wx_main = {};");
script.append(ele.html());
ScriptEngine engine = new ScriptEngineManager()
.getEngineByName("javascript");
NativeArray na = (NativeArray) ((NativeObject) engine.eval(script
.toString())).get("list");
resources = new ArrayList<String>();
for (int i = 0; i < na.getLength(); i++) {
recurrenceMenu(resources, (NativeObject) na.get(i));
}
} else {
resources = new ArrayList<String>(eles.size());
for (Element ele : eles) {
resources.add(String.format(RESOURCE,
ele.getElementsByAttribute("data-id")));
}
}
return resources;
}
private static void recurrenceMenu(List<String> resources,
NativeObject rootObject) {
NativeArray children = (NativeArray) rootObject.get("children");
if (children.getLength() == 0l) {
resources.add(String.format(RESOURCE, rootObject.get("id")
.toString()));
return;
}
for (int i = 0; i < children.getLength(); i++) {
recurrenceMenu(resources, (NativeObject) children.get(i));
}
}
private static Map<String, String> analyCode(String resource)
throws Exception {
Document root = Jsoup.connect(resource).get();
Elements tables = root.getElementsByTag("table");
Map<String, String> error = new HashMap<String, String>();
for (Element table : tables) {
Elements trs = table.getElementsByTag("tr");
String text = trs.first().child(0).text().trim();
if (text.equals("返回码") || text.equals("错误码")) {
for (int i = 1; i < trs.size(); i++) {
error.put(trs.get(i).child(0).text().trim(), trs.get(i)
.child(1).text().trim());
}
}
}
return error;
}
public static Map<String, String> build() throws Exception {
System.err.println("0.开始收集URI资源...");
List<String> resources = collectUrl();
System.err.println("共收集到URI资源:" + resources.size());
System.err.println("1.开始解析URI资源...");
Map<String, String> error = new HashMap<String, String>();
for (int i = 0; i < resources.size(); i++) {
System.err
.println("开始解析第" + (i + 1) + "个URI资源:" + resources.get(i));
Map<String, String> result = analyCode(resources.get(i));
System.err.println(resources.get(i) + ":" + result.size());
error.putAll(result);
}
return error;
}
}

View File

@ -0,0 +1,129 @@
package com.foxinmy.weixin4j.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
/**
* 手机微信商户平台错误码
*
* @className PayErrorBuilder
* @author jy
* @date 2016年5月5日
* @since JDK 1.7
* @see
*/
public class PayErrorBuilder {
private static final String HOME = "https://pay.weixin.qq.com/wiki/doc/api/index.html";
private static final List<String> EXTRA_RESOURCES;
static {
EXTRA_RESOURCES = new ArrayList<String>();
EXTRA_RESOURCES
.add("https://pay.weixin.qq.com/wiki/doc/api/tools/sp_coupon.php?chapter=12_3#");
EXTRA_RESOURCES
.add("https://pay.weixin.qq.com/wiki/doc/api/tools/sp_coupon.php?chapter=12_4");
EXTRA_RESOURCES
.add("https://pay.weixin.qq.com/wiki/doc/api/tools/sp_coupon.php?chapter=12_5");
EXTRA_RESOURCES
.add("https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_5");
EXTRA_RESOURCES
.add("https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_7&index=6");
EXTRA_RESOURCES
.add("https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=16_5");
EXTRA_RESOURCES
.add("https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=16_6");
EXTRA_RESOURCES
.add("https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2");
EXTRA_RESOURCES
.add("https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_3");
EXTRA_RESOURCES
.add("https://pay.weixin.qq.com/wiki/doc/api/external/declarecustom.php?chapter=18_1");
EXTRA_RESOURCES
.add("https://pay.weixin.qq.com/wiki/doc/api/external/declarecustom.php?chapter=18_2");
}
private static List<String> collectUrl() throws Exception {
Document root = Jsoup.connect(HOME).get();
List<String> resources = new ArrayList<String>();
Elements eles = root.getElementsByClass("guide-main");
for (Element ele : eles) {
for (Element li : ele.children()) {
System.err.println(li.child(0).child(1).text() + "资源列表:");
root = Jsoup.connect(li.child(0).absUrl("href")).get();
Elements dls = root.getElementsByClass("menu").first()
.getElementsByTag("dl");
for (Element dl : dls) {
if (dl.child(0).text().equalsIgnoreCase("api列表")) {
for (int i = 1; i < dl.children().size(); i++) {
System.err.println(dl.children().get(i).child(0)
.text());
resources.add(dl.children().get(i).child(0)
.absUrl("href"));
}
break;
}
}
}
}
resources.addAll(EXTRA_RESOURCES);
return resources;
}
private static Map<String, String> analyCode(String resource)
throws Exception {
Document root = Jsoup.connect(resource).get();
Elements eles = root.getElementsByClass("data-box");
Map<String, String> error = new HashMap<String, String>();
String text = "";
StringBuilder desc = new StringBuilder();
for (Element box : eles) {
Elements trs = box.getElementsByTag("tr");
if (trs.isEmpty()) {
continue;
}
text = box.child(0).text().trim();
boolean b1 = text.equals("错误码") || text.equals("返回码");
text = trs.first().text().trim();
boolean b2 = text.equals("错误码") || text.equals("返回码");
if (b1 || b2) {
for (int i = 1; i < trs.size(); i++) {
desc.append(trs.get(i).child(1).text().trim());
for (int j = 2; j < trs.get(i).children().size(); j++) {
desc.append(",").append(
trs.get(i).child(j).text().trim());
}
error.put(trs.get(i).child(0).text().trim(),
desc.toString());
desc.delete(0, desc.length());
}
}
}
return error;
}
public static Map<String, String> builder() throws Exception {
System.err.println("0.开始收集URI资源...");
List<String> resources = collectUrl();
System.err.println("共收集到URI资源:" + resources.size());
System.err.println("1.开始解析URI资源...");
Map<String, String> error = new TreeMap<String, String>();
for (int i = 0; i < resources.size(); i++) {
System.err
.println("开始解析第" + (i + 1) + "个URI资源:" + resources.get(i));
Map<String, String> result = analyCode(resources.get(i));
System.err.println(resources.get(i) + ":" + result.size());
error.putAll(result);
}
System.err.println("共收集到状态码:" + error.size());
return error;
}
}

View File

@ -0,0 +1,40 @@
package com.foxinmy.weixin4j.test;
import java.util.Map;
import java.util.TreeMap;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
/**
* 收集微信企业号错误码
*
* @className QyErrorBuilder
* @author jy
* @date 2016年5月5日
* @since JDK 1.7
* @see
*/
public class QyErrorBuilder {
private static final String HOME = "http://qydev.weixin.qq.com/wiki/index.php?title=%E5%85%A8%E5%B1%80%E8%BF%94%E5%9B%9E%E7%A0%81%E8%AF%B4%E6%98%8E";
private static Map<String, String> analyCode() throws Exception {
Document root = Jsoup.connect(HOME).get();
Elements trs = root.getElementsByTag("tr");
Map<String, String> error = new TreeMap<String, String>();
for (int i = 1; i < trs.size(); i++) {
error.put(trs.get(i).child(0).text().trim(), trs.get(i).child(1)
.text().trim());
}
return error;
}
public static Map<String, String> build() throws Exception {
System.err.println("开始解析URI资源:" + HOME);
Map<String, String> error = analyCode();
System.err.println("共收集到状态码:" + error.size());
return error;
}
}

View File

@ -44,7 +44,6 @@ import com.foxinmy.weixin4j.util.IOUtil;
import com.foxinmy.weixin4j.util.ObjectId; import com.foxinmy.weixin4j.util.ObjectId;
import com.foxinmy.weixin4j.util.RegexUtil; import com.foxinmy.weixin4j.util.RegexUtil;
import com.foxinmy.weixin4j.util.StringUtil; import com.foxinmy.weixin4j.util.StringUtil;
import com.foxinmy.weixin4j.util.WeixinErrorUtil;
/** /**
* 素材相关API * 素材相关API
@ -265,8 +264,8 @@ public class MediaApi extends MpApi {
String disposition = headers String disposition = headers
.getFirst(HttpHeaders.CONTENT_DISPOSITION); .getFirst(HttpHeaders.CONTENT_DISPOSITION);
logger.info("weixin response << " + response.getProtocol() logger.info("weixin response << " + response.getProtocol()
+ response.getStatus().toString() + "[" + contentType + "]->" + response.getStatus().toString() + "[" + contentType
+ disposition); + "]->" + disposition);
if (contentType.contains(ContentType.TEXT_PLAIN.getMimeType()) if (contentType.contains(ContentType.TEXT_PLAIN.getMimeType())
|| contentType.contains(ContentType.APPLICATION_JSON || contentType.contains(ContentType.APPLICATION_JSON
.getMimeType()) .getMimeType())
@ -275,10 +274,6 @@ public class MediaApi extends MpApi {
content.length, Consts.UTF_8.newDecoder(), content.length, Consts.UTF_8.newDecoder(),
JsonResult.class); JsonResult.class);
if (jsonResult.getCode() != 0) { if (jsonResult.getCode() != 0) {
if (StringUtil.isBlank(jsonResult.getDesc())) {
jsonResult.setDesc(WeixinErrorUtil.getText(Integer
.toString(jsonResult.getCode())));
}
throw new WeixinException(Integer.toString(jsonResult throw new WeixinException(Integer.toString(jsonResult
.getCode()), jsonResult.getDesc()); .getCode()), jsonResult.getDesc());
} }

View File

@ -47,7 +47,6 @@ import com.foxinmy.weixin4j.util.IOUtil;
import com.foxinmy.weixin4j.util.ObjectId; import com.foxinmy.weixin4j.util.ObjectId;
import com.foxinmy.weixin4j.util.RegexUtil; import com.foxinmy.weixin4j.util.RegexUtil;
import com.foxinmy.weixin4j.util.StringUtil; import com.foxinmy.weixin4j.util.StringUtil;
import com.foxinmy.weixin4j.util.WeixinErrorUtil;
/** /**
* 媒体相关API * 媒体相关API
@ -236,10 +235,6 @@ public class MediaApi extends QyApi {
content.length, Consts.UTF_8.newDecoder(), content.length, Consts.UTF_8.newDecoder(),
JsonResult.class); JsonResult.class);
if (jsonResult.getCode() != 0) { if (jsonResult.getCode() != 0) {
if (StringUtil.isBlank(jsonResult.getDesc())) {
jsonResult.setDesc(WeixinErrorUtil.getText(Integer
.toString(jsonResult.getCode())));
}
throw new WeixinException(Integer.toString(jsonResult throw new WeixinException(Integer.toString(jsonResult
.getCode()), jsonResult.getDesc()); .getCode()), jsonResult.getDesc());
} }