What is best practice to handle exceptions in Haxe with asynchronous node.js?
This code doesn't display "haha: test", instead it displays "test".
import js.Node;
class Main {
public static function handleRequest(req: NodeHttpServerReq, res: NodeHttpServerResp) {
res.setHeader("Content-Type","text/plain");
res.writeHead(200);
res.end('Hello World\n');
throw "test";
}
public static function main() {
try {
var server = Node.http.createServer(handleRequest);
server.listen(1337,"localhost");
} catch(e: String) {
trace("haha: " + e);
}
trace( 'Server running at http://127.0.0.1:1337/' );
}
}
I know why the exception is not caught. The question is what the best practice for handling exceptions in Haxe is.
Your try / catch
statement is only catching errors thrown by the createServer
and server.listen
method calls and not the logic in the request handler. I'm not 100% sure on this, but my guess is the asynchronous nature of the call means that errors thrown in the handleRequest
method are not caught there also. You'll get the results you expect if you do the following:
import js.Node;
class Main {
public static function handleRequest(req: NodeHttpServerReq, res: NodeHttpServerResp) {
res.setHeader("Content-Type","text/plain");
res.writeHead(200);
res.end('Hello World\n');
//throw "test";
}
public static function main() {
try {
var server = Node.http.createServer(handleRequest);
server.listen(1337,"localhost");
throw "test"; // Throwing the error here will result in it being caught below
} catch(e: String) {
trace("haha: " + e);
}
trace( 'Server running at http://127.0.0.1:1337/' );
}
}
As for best practice on error handling, the bare bones example on haxennode does not include any error handling and uses an inline anonymous function for the success callback (not something I'm sure is entirely compatible with the Haxe philosophy). Otherwise, Haxe with node examples appear to be fairly thin on the ground. However, this stackoverflow thread on handling http errors in node (generally) will probably be useful; note that errors are thrown by the server.listen
method.