-
Notifications
You must be signed in to change notification settings - Fork 257
Expand file tree
/
Copy pathhono.js
More file actions
90 lines (77 loc) · 2.74 KB
/
hono.js
File metadata and controls
90 lines (77 loc) · 2.74 KB
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
81
82
83
84
85
86
87
88
89
90
const { createMiddleware } = require('hono/factory')
const extractRequestInfo = require('./request-info')
const clone = require('@bugsnag/core/lib/clone-client')
const handledState = {
severity: 'error',
unhandled: true,
severityReason: {
type: 'unhandledErrorMiddleware',
attributes: { framework: 'Hono' }
}
}
module.exports = {
name: 'hono',
load: client => {
const requestHandler = createMiddleware(async (c, next) => {
// clone the client to be scoped to this request. If sessions are enabled, start one
const requestClient = clone(client)
if (requestClient._config.autoTrackSessions) {
requestClient.startSession()
}
c.bugsnag = requestClient
// extract request info and pass it to the relevant bugsnag properties
requestClient.addOnError(async (event) => {
const { metadata, request } = await getRequestAndMetadataFromReq(c)
event.request = { ...event.request, ...request }
event.addMetadata('request', metadata)
if (event._handledState.severityReason.type === 'unhandledException') {
event.severity = 'error'
event._handledState = handledState
}
}, true)
await client._clientContext.run(requestClient, next)
})
const errorHandler = createMiddleware(async (c, next) => {
let rethrow = false
try {
// Catch all thrown values from routes by awaiting next() inside a try/catch block.
// This also ensures non-Error throws are attached to the context and processed without causing the route to hang.
await next()
} catch (err) {
c.error = err
rethrow = true
}
if (!c.error) return
if (client._config.autoDetectErrors) {
const event = client.Event.create(c.error, false, handledState, 'hono middleware', 1)
if (c.bugsnag) {
c.bugsnag._notify(event)
} else {
client._logger.warn(
'c.bugsnag is not defined. Make sure the @bugsnag/plugin-hono requestHandler middleware is added first.'
)
const { metadata, request } = await getRequestAndMetadataFromReq(c)
event.request = { ...event.request, ...request }
event.addMetadata('request', metadata)
client._notify(event)
}
}
if (rethrow) throw c.error
})
return { requestHandler, errorHandler }
}
}
const getRequestAndMetadataFromReq = async c => {
const { body, ...requestInfo } = await extractRequestInfo(c)
return {
metadata: requestInfo,
request: {
body,
url: requestInfo.url,
httpMethod: requestInfo.httpMethod,
httpVersion: requestInfo.httpVersion,
headers: requestInfo.headers
}
}
}
module.exports.default = module.exports