@@ -6,6 +6,7 @@ import http from "http"
6
6
import * as httpolyglot from "httpolyglot"
7
7
import * as util from "../common/util"
8
8
import { DefaultedArgs } from "./cli"
9
+ import { isNodeJSErrnoException } from "./util"
9
10
import { handleUpgrade } from "./wsRouter"
10
11
11
12
/**
@@ -33,21 +34,14 @@ export const createApp = async (args: DefaultedArgs): Promise<[Express, Express,
33
34
resolve2 ( )
34
35
}
35
36
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 )
42
38
} )
43
39
44
40
if ( args . socket ) {
45
41
try {
46
42
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 )
51
45
}
52
46
server . listen ( args . socket , resolve )
53
47
} else {
@@ -69,10 +63,46 @@ export const createApp = async (args: DefaultedArgs): Promise<[Express, Express,
69
63
export const ensureAddress = ( server : http . Server ) : string => {
70
64
const addr = server . address ( )
71
65
if ( ! addr ) {
72
- throw new Error ( "server has no address" ) // NOTE @jsjoeio test this line
66
+ throw new Error ( "server has no address" )
73
67
}
74
68
if ( typeof addr !== "string" ) {
75
69
return `http://${ addr . address } :${ addr . port } `
76
70
}
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
+ }
78
108
}
0 commit comments