diff --git a/src/Microsoft.AspNetCore.NodeServices/Content/Node/entrypoint-http.js b/src/Microsoft.AspNetCore.NodeServices/Content/Node/entrypoint-http.js index 76a00ef..9d231f3 100644 --- a/src/Microsoft.AspNetCore.NodeServices/Content/Node/entrypoint-http.js +++ b/src/Microsoft.AspNetCore.NodeServices/Content/Node/entrypoint-http.js @@ -69,18 +69,21 @@ if (!hasSentResult) { hasSentResult = true; if (errorValue) { - res.statusCode = 500; - if (errorValue.stack) { - res.end(errorValue.stack); - } - else { - res.end(errorValue.toString()); - } + respondWithError(res, errorValue); } else if (typeof successValue !== 'string') { // Arbitrary object/number/etc - JSON-serialize it + var successValueJson = void 0; + try { + successValueJson = JSON.stringify(successValue); + } + catch (ex) { + // JSON serialization error - pass it back to .NET + respondWithError(res, ex); + return; + } res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(successValue)); + res.end(JSON.stringify(successValueJson)); } else { // String - can bypass JSON-serialization altogether @@ -129,6 +132,10 @@ .on('data', function (chunk) { requestBodyAsString += chunk; }) .on('end', function () { callback(JSON.parse(requestBodyAsString)); }); } + function respondWithError(res, errorValue) { + res.statusCode = 500; + res.end(errorValue.stack || errorValue.toString()); + } /***/ }, diff --git a/src/Microsoft.AspNetCore.NodeServices/TypeScript/HttpNodeInstanceEntryPoint.ts b/src/Microsoft.AspNetCore.NodeServices/TypeScript/HttpNodeInstanceEntryPoint.ts index 431810e..5bb8623 100644 --- a/src/Microsoft.AspNetCore.NodeServices/TypeScript/HttpNodeInstanceEntryPoint.ts +++ b/src/Microsoft.AspNetCore.NodeServices/TypeScript/HttpNodeInstanceEntryPoint.ts @@ -17,17 +17,19 @@ const server = http.createServer((req, res) => { if (!hasSentResult) { hasSentResult = true; if (errorValue) { - res.statusCode = 500; - - if (errorValue.stack) { - res.end(errorValue.stack); - } else { - res.end(errorValue.toString()); - } + respondWithError(res, errorValue); } else if (typeof successValue !== 'string') { // Arbitrary object/number/etc - JSON-serialize it + let successValueJson: string; + try { + successValueJson = JSON.stringify(successValue); + } catch (ex) { + // JSON serialization error - pass it back to .NET + respondWithError(res, ex); + return; + } res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(successValue)); + res.end(JSON.stringify(successValueJson)); } else { // String - can bypass JSON-serialization altogether res.setHeader('Content-Type', 'text/plain'); @@ -82,3 +84,8 @@ function readRequestBodyAsJson(request, callback) { .on('data', chunk => { requestBodyAsString += chunk; }) .on('end', () => { callback(JSON.parse(requestBodyAsString)); }); } + +function respondWithError(res: http.ServerResponse, errorValue: any) { + res.statusCode = 500; + res.end(errorValue.stack || errorValue.toString()); +}