Skip to content

Instantly share code, notes, and snippets.

@thislight
Created March 30, 2019 09:49
Show Gist options
  • Save thislight/d8de0a18898ac7852d27970c7d43f003 to your computer and use it in GitHub Desktop.
Save thislight/d8de0a18898ac7852d27970c7d43f003 to your computer and use it in GitHub Desktop.
Protection call in dart

Call function in protection mode, it's more comfortable way to handle errors.
How to use:

void _handleMessage(WebSocket wsock, String data){
    var parts = pcall(() => _parseMessage(data), (error, st){
      _messageFormatNotAcceptedHandler(wsock, error, st);
    });
    if (isFail(parts)) return;
    var command = parts[0];
    Map playload = pcall(() => JSON.decode(parts[1]), (error, st){
      _messageFormatNotAcceptedHandler(wsock, error, st);
    });
    callCommand(wsock, command, playload);
  }

pcallAsync just a function call pcall and return the result with typing mark Future for type checking.

typedef void CodeProtectionHandler(dynamic error, StackTrace trace);
enum _PcallFailMark {
Fail
}
dynamic pcall(dynamic target, CodeProtectionHandler cph){
if (target is Function){
try {
return target();
} catch (e,st){
cph(e,st);
return _PcallFailMark.Fail;
}
} else if(target is Future) {
return target.catchError((e,[st]){
cph(e,st);
return _PcallFailMark.Fail;
});
}
return null;
}
FutureOr<_PcallFailMark> pcallAsync<R>(Future target, CodeProtectionHandler cph){
return pcall(target, cph);
}
bool isFail(dynamic pcallResult){
if (pcallResult is _PcallFailMark && pcallResult == _PcallFailMark.Fail) return false;
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment