MCPcopy
hub / github.com/koajs/koa / onerror

Function onerror

lib/context.js:106–162  ·  view source on GitHub ↗

* Default error handling. * * @param {Error} err * @api private

(err)

Source from the content-addressed store, hash-verified

104 */
105
106 onerror (err) {
107 // don't do anything if there is no error.
108 // this allows you to pass `this.onerror`
109 // to node-style callbacks.
110 if (err == null) return
111
112 // When dealing with cross-globals a normal `instanceof` check doesn't work properly.
113 // See https://github.com/koajs/koa/issues/1466
114 // We can probably remove it once jest fixes https://github.com/facebook/jest/issues/2549.
115 const isNativeError =
116 Object.prototype.toString.call(err) === '[object Error]' ||
117 err instanceof Error
118 if (!isNativeError) err = new Error(util.format('non-error thrown: %j', err))
119
120 let headerSent = false
121 if (this.headerSent || !this.writable) {
122 headerSent = err.headerSent = true
123 }
124
125 // delegate
126 this.app.emit('error', err, this)
127
128 // nothing we can do here other
129 // than delegate to the app-level
130 // handler and log.
131 if (headerSent) {
132 return
133 }
134
135 const { res } = this
136
137 // first unset all headers
138 /* istanbul ignore else */
139 if (typeof res.getHeaderNames === 'function') {
140 res.getHeaderNames().forEach(name => res.removeHeader(name))
141 } else {
142 res._headers = {} // Node < 7.7
143 }
144
145 // then set those specified
146 this.set(err.headers)
147
148 // force text/plain
149 this.type = 'text'
150
151 let statusCode = err.status || err.statusCode
152
153 // default to 500
154 if (typeof statusCode !== 'number' || !statuses.message[statusCode]) statusCode = 500
155
156 // respond
157 const code = statuses.message[statusCode]
158 const msg = err.expose ? err.message : code
159 this.status = err.status = statusCode
160 this.length = Buffer.byteLength(msg)
161 res.end(msg)
162 },
163

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…