Skip to content

Commit

Permalink
Merge branch 'danprince-handle-dev-server-errors'
Browse files Browse the repository at this point in the history
  • Loading branch information
FredKSchott committed Jun 12, 2020
2 parents 4f9403b + 1e17cbd commit cfebcbf
Showing 1 changed file with 17 additions and 13 deletions.
30 changes: 17 additions & 13 deletions src/commands/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -461,12 +461,7 @@ export async function command(commandOptions: CommandOptions) {
}
}

const createServer = credentials
? (requestHandler) =>
http2.createSecureServer({...credentials!, allowHTTP1: true}, requestHandler)
: (requestHandler) => http.createServer(requestHandler);

const server = createServer(async (req, res) => {
async function requestHandler(req: http.IncomingMessage, res: http.ServerResponse) {
const reqUrl = req.url!;
const reqUrlHmrParam = reqUrl.includes('?mtime=') && reqUrl.split('?')[1];
let reqPath = decodeURI(url.parse(reqUrl).pathname!);
Expand Down Expand Up @@ -683,13 +678,7 @@ export async function command(commandOptions: CommandOptions) {
}

// 2. Load the file from disk. We'll need it to check the cold cache or build from scratch.
let fileContents: string;
try {
fileContents = await fs.readFile(fileLoc, getEncodingType(requestedFileExt));
} catch (err) {
console.error(fileLoc, err);
return sendError(res, 500);
}
const fileContents = await fs.readFile(fileLoc, getEncodingType(requestedFileExt));

// 3. Check the persistent cache. If found, serve it via a "trust-but-verify" strategy.
// Build it after sending, and if it no longer matches then assume the entire cache is suspect.
Expand Down Expand Up @@ -799,6 +788,21 @@ export async function command(commandOptions: CommandOptions) {
}

sendFile(req, res, wrappedResponse, responseFileExt);
}

const createServer = credentials
? (requestHandler) =>
http2.createSecureServer({...credentials!, allowHTTP1: true}, requestHandler)
: (requestHandler) => http.createServer(requestHandler);

const server = createServer(async (req, res) => {
try {
return await requestHandler(req, res);
} catch (err) {
console.error(`[500] ${req.url}`);
console.error(err);
return sendError(res, 500);
}
})
.on('error', (err: Error) => {
console.error(chalk.red(` ✘ Failed to start server at port ${chalk.bold(port)}.`), err);
Expand Down

0 comments on commit cfebcbf

Please sign in to comment.