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

Function onerror

lib/context.js:106–162  ·  lib/context.js::onerror

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

(err)

Source from the content-addressed store, hash-verified

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