Skip to content

Commit

Permalink
fix(server): correctly handle errors on listenThe Promise constructor…
Browse files Browse the repository at this point in the history
… doesn't automatically catch errors if its handlerfunction is async. Use try/catch to avoid unhandled rejections.If the server is closed because the port is already in used, use anon-zero exit code and log it as an error. (#1175)
  • Loading branch information
targos authored and thetutlage committed Dec 2, 2019
1 parent be417ca commit ebdf015
Showing 1 changed file with 18 additions and 13 deletions.
31 changes: 18 additions & 13 deletions src/Ignitor/HttpServer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,8 @@ export class HttpServer {

this._server.instance!.on('error', async (error: NodeJS.ErrnoException) => {
if (error.code === 'EADDRINUSE') {
this._logger.trace(`Port in use, closing server`)
this._logger.error(`Port in use, closing server`)
process.exitCode = 1
return
}

Expand Down Expand Up @@ -175,18 +176,22 @@ export class HttpServer {
* Starts the http server a given host and port
*/
public listen () {
return new Promise(async (resolve) => {
await this._bootstrapper.executeReadyHooks()

const Env = this.application.container.use('Adonis/Core/Env')
const host = Env.get('HOST', '0.0.0.0') as string
const port = Number(Env.get('PORT', '3333') as string)

this._server.instance!.listen(port, host, () => {
this._logger.info('started server on %s:%s', host, port)
this.application.isReady = true
resolve()
})
return new Promise(async (resolve, reject) => {
try {
await this._bootstrapper.executeReadyHooks()

const Env = this.application.container.use('Adonis/Core/Env')
const host = Env.get('HOST', '0.0.0.0') as string
const port = Number(Env.get('PORT', '3333') as string)

this._server.instance!.listen(port, host, () => {
this._logger.info('started server on %s:%s', host, port)
this.application.isReady = true
resolve()
})
} catch (error) {
reject(error)
}
})
}

Expand Down

0 comments on commit ebdf015

Please sign in to comment.