(thenable, reply, store)
| 10 | const channels = diagnostics.tracingChannel('fastify.request.handler') |
| 11 | |
| 12 | function wrapThenable (thenable, reply, store) { |
| 13 | if (store) store.async = true |
| 14 | thenable.then(function (payload) { |
| 15 | if (reply[kReplyHijacked] === true) { |
| 16 | return |
| 17 | } |
| 18 | |
| 19 | if (store) { |
| 20 | channels.asyncStart.publish(store) |
| 21 | } |
| 22 | |
| 23 | try { |
| 24 | // this is for async functions that are using reply.send directly |
| 25 | // |
| 26 | // since wrap-thenable will be called when using reply.send directly |
| 27 | // without actual return. the response can be sent already or |
| 28 | // the request may be terminated during the reply. in this situation, |
| 29 | // it require an extra checking of request.aborted to see whether |
| 30 | // the request is killed by client. |
| 31 | if (payload !== undefined || // |
| 32 | (reply.sent === false && // |
| 33 | reply.raw.headersSent === false && |
| 34 | reply.request.raw.aborted === false && |
| 35 | reply.request.socket && |
| 36 | !reply.request.socket.destroyed |
| 37 | ) |
| 38 | ) { |
| 39 | // we use a try-catch internally to avoid adding a catch to another |
| 40 | // promise, increase promise perf by 10% |
| 41 | try { |
| 42 | reply.send(payload) |
| 43 | } catch (err) { |
| 44 | reply[kReplyIsError] = true |
| 45 | reply.send(err) |
| 46 | } |
| 47 | } |
| 48 | } finally { |
| 49 | if (store) { |
| 50 | channels.asyncEnd.publish(store) |
| 51 | } |
| 52 | } |
| 53 | }, function (err) { |
| 54 | if (store) { |
| 55 | store.error = err |
| 56 | // Set status code before publishing so subscribers see the correct value |
| 57 | setErrorStatusCode(reply, err) |
| 58 | channels.error.publish(store) // note that error happens before asyncStart |
| 59 | channels.asyncStart.publish(store) |
| 60 | } |
| 61 | |
| 62 | try { |
| 63 | if (reply.sent === true) { |
| 64 | reply.log.error({ err }, 'Promise errored, but reply.sent = true was set') |
| 65 | return |
| 66 | } |
| 67 | |
| 68 | reply[kReplyIsError] = true |
| 69 |
no test coverage detected