@error-reporting/java 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -2
- package/package.json +15 -4
- package/src/main/java/io/errorreporting/ErrorReporting.java +159 -0
package/README.md
CHANGED
|
@@ -1,3 +1,23 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @error-reporting/java
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
需要 JDK 11 或以上。npm 包内提供 Java 源码,将它加入 Java 项目的编译输入。
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install @error-reporting/java
|
|
7
|
+
javac --release 11 -encoding UTF-8 -d build/classes node_modules/@error-reporting/java/src/main/java/io/errorreporting/ErrorReporting.java
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
```java
|
|
11
|
+
import io.errorreporting.ErrorReporting;
|
|
12
|
+
import java.util.Map;
|
|
13
|
+
|
|
14
|
+
// 在应用入口调用一次。
|
|
15
|
+
ErrorReporting.Init(Map.of("dsn", dsn, "environment", "production", "release", "git-sha"));
|
|
16
|
+
|
|
17
|
+
// 在 catch 块里补报已处理的异常。
|
|
18
|
+
ErrorReporting.CaptureException(error, Map.of("requestId", "request-42"));
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
`Init()` 也可从 `ERROR_REPORTING_DSN`、`ERROR_REPORTING_ENVIRONMENT` 和 `ERROR_REPORTING_RELEASE` 读取配置,
|
|
22
|
+
并安装 JVM 默认的未捕获异常处理器。线程或框架有独立错误处理器时,可在其中调用 `CaptureException`。
|
|
23
|
+
同步上报成功返回事件 ID,失败返回 `null`。
|
package/package.json
CHANGED
|
@@ -1,6 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@error-reporting/java",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Error Reporting Platform SDK for Java",
|
|
5
|
+
"files": [
|
|
6
|
+
"src/main/java/io/errorreporting/ErrorReporting.java"
|
|
7
|
+
],
|
|
8
|
+
"publishConfig": {
|
|
9
|
+
"access": "public",
|
|
10
|
+
"registry": "https://registry.npmjs.org/"
|
|
11
|
+
},
|
|
12
|
+
"repository": {
|
|
13
|
+
"type": "git",
|
|
14
|
+
"url": "git+https://gitee.com/qglove/error-reporting-platform.git",
|
|
15
|
+
"directory": "packages/native/java"
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
package io.errorreporting;
|
|
2
|
+
|
|
3
|
+
import java.io.IOException;
|
|
4
|
+
import java.net.URI;
|
|
5
|
+
import java.net.http.HttpClient;
|
|
6
|
+
import java.net.http.HttpRequest;
|
|
7
|
+
import java.net.http.HttpResponse;
|
|
8
|
+
import java.time.Duration;
|
|
9
|
+
import java.time.Instant;
|
|
10
|
+
import java.util.Map;
|
|
11
|
+
import java.util.UUID;
|
|
12
|
+
|
|
13
|
+
/** Sends Java exceptions to the Error Reporting Platform. */
|
|
14
|
+
public final class ErrorReporting {
|
|
15
|
+
private static final Duration TIMEOUT = Duration.ofSeconds(2);
|
|
16
|
+
private static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(TIMEOUT).build();
|
|
17
|
+
private static volatile Config config;
|
|
18
|
+
|
|
19
|
+
private ErrorReporting() {}
|
|
20
|
+
|
|
21
|
+
/** Initialize with ERROR_REPORTING_* environment variables. */
|
|
22
|
+
public static void Init() {
|
|
23
|
+
Init(Map.of());
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Configure the DSN once and chain the existing uncaught exception handler.
|
|
27
|
+
* @param options Optional dsn, environment and release overrides.
|
|
28
|
+
*/
|
|
29
|
+
public static synchronized void Init(Map<String, String> options) {
|
|
30
|
+
if (config != null) {
|
|
31
|
+
throw new IllegalStateException("error reporting is already initialized");
|
|
32
|
+
}
|
|
33
|
+
URI dsn;
|
|
34
|
+
try {
|
|
35
|
+
dsn = URI.create(option(options, "dsn", "ERROR_REPORTING_DSN", "").trim());
|
|
36
|
+
} catch (IllegalArgumentException ignored) {
|
|
37
|
+
throw new IllegalArgumentException("invalid error reporting DSN");
|
|
38
|
+
}
|
|
39
|
+
String scheme = dsn.getScheme();
|
|
40
|
+
String path = dsn.getRawPath();
|
|
41
|
+
String key = dsn.getRawUserInfo();
|
|
42
|
+
if (!("http".equals(scheme) || "https".equals(scheme)) || dsn.getHost() == null
|
|
43
|
+
|| key == null || !key.matches("[a-zA-Z0-9]+")
|
|
44
|
+
|| path == null || !path.matches("/[0-9]{1,24}/?")
|
|
45
|
+
|| dsn.getRawQuery() != null || dsn.getRawFragment() != null) {
|
|
46
|
+
throw new IllegalArgumentException("invalid error reporting DSN");
|
|
47
|
+
}
|
|
48
|
+
String port = dsn.getPort() < 0 ? "" : ":" + dsn.getPort();
|
|
49
|
+
URI endpoint = URI.create(scheme + "://" + dsn.getHost() + port + "/api" + path.replaceFirst("/$", "") + "/envelope/");
|
|
50
|
+
config = new Config(endpoint, key, option(options, "environment", "ERROR_REPORTING_ENVIRONMENT", "development"),
|
|
51
|
+
option(options, "release", "ERROR_REPORTING_RELEASE", ""));
|
|
52
|
+
Thread.UncaughtExceptionHandler previous = Thread.getDefaultUncaughtExceptionHandler();
|
|
53
|
+
Thread.setDefaultUncaughtExceptionHandler((thread, failure) -> {
|
|
54
|
+
CaptureException(failure);
|
|
55
|
+
if (previous != null) {
|
|
56
|
+
previous.uncaughtException(thread, failure);
|
|
57
|
+
} else if (!(failure instanceof ThreadDeath)) {
|
|
58
|
+
System.err.print("Exception in thread \"" + thread.getName() + "\" ");
|
|
59
|
+
failure.printStackTrace(System.err);
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Send a handled exception without a request ID. */
|
|
65
|
+
public static String CaptureException(Throwable error) {
|
|
66
|
+
return CaptureException(error, Map.of());
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Send an exception and return the event ID, or null on failure.
|
|
70
|
+
* @param error Exception to report.
|
|
71
|
+
* @param context Optional requestId for this event.
|
|
72
|
+
*/
|
|
73
|
+
public static String CaptureException(Throwable error, Map<String, String> context) {
|
|
74
|
+
Config active = config;
|
|
75
|
+
if (active == null || error == null) {
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
try {
|
|
79
|
+
String id = UUID.randomUUID().toString().replace("-", "");
|
|
80
|
+
String requestId = context.getOrDefault("requestId", "");
|
|
81
|
+
String tags = requestId.isEmpty() ? "{}" : "{\"request_id\":" + quote(requestId, 128) + "}";
|
|
82
|
+
String data = "{\"event_id\":\"" + id + "\",\"timestamp\":\"" + Instant.now()
|
|
83
|
+
+ "\",\"platform\":\"java\",\"environment\":" + quote(active.environment, 80)
|
|
84
|
+
+ ",\"release\":" + quote(active.release, 160) + ",\"tags\":" + tags
|
|
85
|
+
+ ",\"exception\":{\"values\":[{\"type\":" + quote(error.getClass().getName(), 120)
|
|
86
|
+
+ ",\"value\":" + quote(error.getMessage(), 2000)
|
|
87
|
+
+ ",\"stacktrace\":{\"frames\":[" + stack(error) + "]}}]}}";
|
|
88
|
+
String envelope = "{\"event_id\":\"" + id + "\"}\n{\"type\":\"event\"}\n" + data + "\n";
|
|
89
|
+
HttpRequest request = HttpRequest.newBuilder(active.endpoint).timeout(TIMEOUT)
|
|
90
|
+
.header("Content-Type", "application/x-sentry-envelope")
|
|
91
|
+
.header("X-Sentry-Auth", "Sentry sentry_version=7, sentry_key=" + active.key)
|
|
92
|
+
.POST(HttpRequest.BodyPublishers.ofString(envelope)).build();
|
|
93
|
+
int status = HTTP.send(request, HttpResponse.BodyHandlers.discarding()).statusCode();
|
|
94
|
+
return status >= 200 && status < 300 ? id : null;
|
|
95
|
+
} catch (InterruptedException ignored) {
|
|
96
|
+
Thread.currentThread().interrupt();
|
|
97
|
+
return null;
|
|
98
|
+
} catch (IOException | RuntimeException ignored) {
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Serialize the most recent frames, with the throw site last. */
|
|
104
|
+
private static String stack(Throwable error) {
|
|
105
|
+
StackTraceElement[] trace = error.getStackTrace();
|
|
106
|
+
StringBuilder result = new StringBuilder();
|
|
107
|
+
for (int i = Math.min(trace.length, 50) - 1; i >= 0; --i) {
|
|
108
|
+
StackTraceElement frame = trace[i];
|
|
109
|
+
result.append("{\"filename\":").append(quote(frame.getFileName(), 500))
|
|
110
|
+
.append(",\"function\":").append(quote(frame.getClassName() + "." + frame.getMethodName(), 180))
|
|
111
|
+
.append(",\"lineno\":").append(frame.getLineNumber()).append('}');
|
|
112
|
+
if (i != 0) {
|
|
113
|
+
result.append(',');
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return result.toString();
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Encode a bounded JSON string without introducing a runtime dependency. */
|
|
120
|
+
private static String quote(String value, int limit) {
|
|
121
|
+
StringBuilder out = new StringBuilder("\"");
|
|
122
|
+
if (value != null) {
|
|
123
|
+
for (int i = 0; i < Math.min(limit, value.length()); i++) {
|
|
124
|
+
char character = value.charAt(i);
|
|
125
|
+
if (character == '"' || character == '\\') {
|
|
126
|
+
out.append('\\').append(character);
|
|
127
|
+
} else if (character < 32 || Character.isSurrogate(character)) {
|
|
128
|
+
out.append(String.format("\\u%04x", (int) character));
|
|
129
|
+
} else {
|
|
130
|
+
out.append(character);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return out.append('"').toString();
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Resolve an explicit option, an environment variable and then its default. */
|
|
138
|
+
private static String option(Map<String, String> options, String name, String variable, String fallback) {
|
|
139
|
+
String value = options.get(name);
|
|
140
|
+
if (value == null || value.isEmpty()) {
|
|
141
|
+
value = System.getenv(variable);
|
|
142
|
+
}
|
|
143
|
+
return value == null || value.isEmpty() ? fallback : value;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
private static final class Config {
|
|
147
|
+
final URI endpoint;
|
|
148
|
+
final String key;
|
|
149
|
+
final String environment;
|
|
150
|
+
final String release;
|
|
151
|
+
|
|
152
|
+
Config(URI endpoint, String key, String environment, String release) {
|
|
153
|
+
this.endpoint = endpoint;
|
|
154
|
+
this.key = key;
|
|
155
|
+
this.environment = environment;
|
|
156
|
+
this.release = release;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|