forked from 0xZhangKe/WebSocketDemo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AppResponseDispatcher.java
80 lines (75 loc) · 2.9 KB
/
AppResponseDispatcher.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.zhangke.smaple.dispatersample;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.TypeReference;
import com.zhangke.websocket.SimpleDispatcher;
import com.zhangke.websocket.dispatcher.ResponseDelivery;
import com.zhangke.websocket.response.ErrorResponse;
import com.zhangke.websocket.response.Response;
import com.zhangke.websocket.response.ResponseFactory;
/**
* 消息分发器
* <p>
* Created by ZhangKe on 2018/6/27.
*/
public class AppResponseDispatcher extends SimpleDispatcher {
/**
* JSON 数据格式错误
*/
public static final int JSON_ERROR = 11;
/**
* code 码错误
*/
public static final int CODE_ERROR = 12;
@Override
public void onMessage(String message, ResponseDelivery delivery) {
try {
CommonResponseEntity response = JSON.parseObject(message, new TypeReference<CommonResponseEntity>() {
});
if (response.getCode() >= 1000 && response.getCode() < 2000) {
delivery.onMessage(message, response);
} else {
ErrorResponse errorResponse = ResponseFactory.createErrorResponse();
errorResponse.setErrorCode(CODE_ERROR);
Response<String> textResponse = ResponseFactory.createTextResponse();
textResponse.setResponseData(message);
errorResponse.setResponseData(textResponse);
errorResponse.setReserved(response);
onSendDataError(errorResponse, delivery);
}
} catch (JSONException e) {
ErrorResponse errorResponse = ResponseFactory.createErrorResponse();
Response<String> textResponse = ResponseFactory.createTextResponse();
textResponse.setResponseData(message);
errorResponse.setResponseData(textResponse);
errorResponse.setErrorCode(JSON_ERROR);
errorResponse.setCause(e);
onSendDataError(errorResponse, delivery);
}
}
/**
* 统一处理错误信息,
* 界面上可使用 ErrorResponse#getDescription() 来当做提示语
*/
@Override
public void onSendDataError(ErrorResponse error, ResponseDelivery delivery) {
switch (error.getErrorCode()) {
case ErrorResponse.ERROR_NO_CONNECT:
error.setDescription("网络错误");
break;
case ErrorResponse.ERROR_UN_INIT:
error.setDescription("连接未初始化");
break;
case ErrorResponse.ERROR_UNKNOWN:
error.setDescription("未知错误");
break;
case JSON_ERROR:
error.setDescription("数据格式异常");
break;
case CODE_ERROR:
error.setDescription("响应码错误");
break;
}
delivery.onSendDataError(error);
}
}