我想使用dart开发一个web服务+ web套接字服务器,但问题是我不能确保服务器的高可用性,因为隔离中存在未捕获的异常。
当然,我已经尝试了捕获我的main函数,但这还不够。
如果在未来的then()部分发生异常,服务器将崩溃。
这意味着一个有缺陷的请求可能会使服务器宕机。
我意识到这是一个open issue,但是有没有办法在不使VM崩溃的情况下阻止任何崩溃,以便服务器可以继续为其他请求服务?
谢谢。
发布于 2013-06-24 08:54:36
我在过去所做的是使用主隔离来启动一个子隔离,它托管实际的web服务器。当您启动一个隔离时,您可以将一个“未捕获的异常”处理程序传递给子隔离(我还认为您应该能够在顶级注册一个,以防止这个特定的问题,正如原始问题中的问题所提到的那样)。
示例:
import 'dart:isolate';
void main() {
// Spawn a child isolate
spawnFunction(isolateMain, uncaughtExceptionHandler);
}
void isolateMain() {
// this is the "real" entry point of your app
// setup http servers and listen etc...
}
bool uncaughtExceptionHandler(ex) {
// TODO: add logging!
// respawn a new child isolate.
spawnFunction(isolateMain, uncaughtException);
return true; // we've handled the uncaught exception
}
发布于 2013-06-24 18:06:39
Chris Buckett为您提供了一个在服务器出现故障时重新启动服务器的好方法。但是,您仍然不希望您的服务器宕机。
try-catch
只适用于同步代码。
doSomething() {
try {
someSynchronousFunc();
someAsyncFunc().then(() => print('foo'));
} catch (e) {
// ...
}
}
当异步方法完成或失败时,它发生在程序使用doSomething
方法完成之后的很长一段时间。
当您编写异步代码时,通常通过返回一个future来启动一个方法是一个好主意:
Future doSomething() {
return new Future(() {
// your code here.
var a = b + 5; // throws and is caught.
return someAsyncCall(); // Errors are forwarded if you return the Future directly.
});
}
这确保了如果您有抛出的代码,它会捕获它们,然后调用者可以catchError()
它们。
如果你以这种方式编写,你会有更少的崩溃,假设你至少在顶层有一些错误处理。
无论何时调用返回Future的方法,要么直接返回它(如上图所示),要么返回它的catchError()
,这样您就可以在本地处理可能的错误。
主页上有a great lengthy article,你应该去看看。
https://stackoverflow.com/questions/17271178
复制