Skip to content

Commit

Permalink
Make sure that the server builder propagates init errors properly
Browse files Browse the repository at this point in the history
Signed-off-by: Fredrik Adelöw <freben@gmail.com>
  • Loading branch information
freben committed Nov 11, 2021
1 parent f979fcf commit a8732a1
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 16 deletions.
12 changes: 12 additions & 0 deletions .changeset/rich-pillows-cough.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@backstage/backend-common': patch
---

Make sure that server builder `start()` propagates errors (such as failing to bind to the required port) properly and doesn't resolve the promise prematurely.

After this change, the backend logger will be able to actually capture the error as it happens:

```
2021-11-11T10:54:21.334Z backstage info Initializing http server
2021-11-11T10:54:21.335Z backstage error listen EADDRINUSE: address already in use :::7000 code=EADDRINUSE errno=-48 syscall=listen address=:: port=7000
```
34 changes: 19 additions & 15 deletions packages/backend-common/src/service/lib/ServiceBuilderImpl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,25 +176,29 @@ export class ServiceBuilderImpl implements ServiceBuilder {
: createHttpServer(app, logger);

return new Promise((resolve, reject) => {
app.on('error', e => {
logger.error(`Failed to start up on port ${port}, ${e}`);
function handleStartupError(e: unknown) {
server.close();
reject(e);
});
}

app.on('error', handleStartupError);
server.on('error', handleStartupError);

const stoppableServer = stoppable(
server.listen(port, host, () => {
logger.info(`Listening on ${host}:${port}`);
}),
0,
);
server.listen(port, host, () => {
app.off('error', handleStartupError);
server.off('error', handleStartupError);

useHotCleanup(this.module, () =>
stoppableServer.stop((e: any) => {
if (e) console.error(e);
}),
);
const stoppableServer = stoppable(server, 0);

resolve(stoppableServer);
useHotCleanup(this.module, () =>
stoppableServer.stop((e: any) => {
if (e) console.error(e);
}),
);

logger.info(`Listening on ${host}:${port}`);
resolve(stoppableServer);
});
});
}

Expand Down
2 changes: 1 addition & 1 deletion packages/backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ async function main() {

await service.start().catch(err => {
logger.error(err);
process.exit(1);
throw err;
});
}

Expand Down

0 comments on commit a8732a1

Please sign in to comment.