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 / catchstatement is only catching errors thrown by thecreateServerandserver.listenmethod 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 thehandleRequestmethod are not caught there also. You’ll get the results you expect if you do the following: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.listenmethod.