what is best practice to handle exceptions in haxe with asynchronous node.js?
This code dont displays "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 get catched. The question is what is best practice for handling exceptions in HaXe.
I suggest you try haxe-continuation, which handle Node.js exceptions as return values. See this example.
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.
I think you should avoid the try/catch entirely and favor a more NodeJS oriented strategy. In handleRequest
you should be able to do req.abort()
and intercept the error by listening at the clientError
event on server
.
Disclaimer: I am not using NodeJS so my details could be wrong but the general concept should be correct ;)