-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
45 lines (32 loc) · 1.23 KB
/
index.ts
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
import { MiddlewareHandlerContext } from "https://deno.land/x/[email protected]/server.ts";
import { createReporter } from "https://deno.land/x/[email protected]/mod.ts";
const ga = createReporter();
export async function gaMiddleware(req: Request, ctx: MiddlewareHandlerContext): Promise<Response> {
const start = performance.now();
const res = await ctx.next();
if (!res.headers.get('content-type')?.includes("text/html")) {
return res;
}
notifyGA();
return res
async function notifyGA () {
const body = await (await res.clone()).text();
ga(req, ctx, res, start, extractErrorFromFreshBody(body));
}
}
export function extractErrorFromFreshBody (body: string): Error | undefined {
if (!/An error occurr?ed during route handling or page rendering./.test(body)) {
return;
}
const extractor = new RegExp('<pre [^<]+>([^<]+)<\/pre>');
const errorString = (extractor.exec(body)|| [])[1];
if (!errorString) {
return;
}
const [firstLine] = errorString.split("\n");
const message = firstLine.split(":")[1].split("\n")[0].trim()
const error = new Error(message)
error.name = firstLine.split(":")[0].trim()
error.stack = errorString
return error
}