@@ -6,6 +6,7 @@ import http from "http"
66import * as httpolyglot from "httpolyglot"
77import * as util from "../common/util"
88import { DefaultedArgs } from "./cli"
9+ import { isNodeJSErrnoException } from "./util"
910import { handleUpgrade } from "./wsRouter"
1011
1112/**
@@ -33,21 +34,14 @@ export const createApp = async (args: DefaultedArgs): Promise<[Express, Express,
3334 resolve2 ( )
3435 }
3536 server . on ( "error" , ( err ) => {
36- if ( ! resolved ) {
37- reject ( err )
38- } else {
39- // Promise resolved earlier so this is an unrelated error.
40- util . logError ( logger , "http server error" , err )
41- }
37+ handleServerError ( resolved , err , reject )
4238 } )
4339
4440 if ( args . socket ) {
4541 try {
4642 await fs . unlink ( args . socket )
47- } catch ( error ) {
48- if ( error . code !== "ENOENT" ) {
49- logger . error ( error . message )
50- }
43+ } catch ( error : any ) {
44+ handleArgsSocketCatchError ( error )
5145 }
5246 server . listen ( args . socket , resolve )
5347 } else {
@@ -69,10 +63,46 @@ export const createApp = async (args: DefaultedArgs): Promise<[Express, Express,
6963export const ensureAddress = ( server : http . Server ) : string => {
7064 const addr = server . address ( )
7165 if ( ! addr ) {
72- throw new Error ( "server has no address" ) // NOTE @jsjoeio test this line
66+ throw new Error ( "server has no address" )
7367 }
7468 if ( typeof addr !== "string" ) {
7569 return `http://${ addr . address } :${ addr . port } `
7670 }
77- return addr // NOTE@jsjoeio test this line
71+ return addr
72+ }
73+
74+ /**
75+ * Handles error events from the server.
76+ *
77+ * If the outlying Promise didn't resolve
78+ * then we reject with the error.
79+ *
80+ * Otherwise, we log the error.
81+ *
82+ * We extracted into a function so that we could
83+ * test this logic more easily.
84+ */
85+ export const handleServerError = ( resolved : boolean , err : Error , reject : ( err : Error ) => void ) => {
86+ // Promise didn't resolve earlier so this means it's an error
87+ // that occurs before the server can successfully listen.
88+ // Possibly triggered by listening on an invalid port or socket.
89+ if ( ! resolved ) {
90+ reject ( err )
91+ } else {
92+ // Promise resolved earlier so this is an unrelated error.
93+ util . logError ( logger , "http server error" , err )
94+ }
95+ }
96+
97+ /**
98+ * Handles the error that occurs in the catch block
99+ * after we try fs.unlink(args.socket).
100+ *
101+ * We extracted into a function so that we could
102+ * test this logic more easily.
103+ */
104+ export const handleArgsSocketCatchError = ( error : any ) => {
105+ if ( ! isNodeJSErrnoException ( error ) || error . code !== "ENOENT" ) {
106+ logger . error ( error . message ? error . message : error )
107+ }
78108}
0 commit comments