This project is read-only.

Errors across AppDomains

Jul 24, 2010 at 12:10 AM

I have a new problem related to execution in a sandboxed AppDomain.

If the Python code I'm executing (through source.Execute(scope)) raises an error, the Execute method throws an exception because it wants Full Trust.

E.g. trying to execute "raise TypeError" results in a demand for full trust.

This is very annoying, because I would like to display error messages to users when an error is raised by Python code in its sandbox, but currently all I can say is that the request for Full Trust failed (on purpose since it's inside a restricted sandbox).

Jul 29, 2010 at 5:42 PM

The problem is that the exception serialization requires full trust.

You can use ExecuteAndWrap API on ScriptEngine to get an ObjectHandle to the exception. This keeps the exception object in the remote app-domain and thus aviods serialization. You can then use a subclass of MarshalByRefObject to access the exception like so:

public class ExHandler : MarshalByRefObject {
  public string HandleException(ObjectHandle e) {
    return e.Unwrap().ToString();

ExHandler remoteHandler = (ExHandler)domain.CreateInstanceAndUnwrap(typeof(ExHandler).Assembly.FullName, typeof(ExHandler).FullName);

ObjectHandle exception;
ObjectHandle result = engine.ExecuteAndWrap(@"
def foo():
  raise TypeError

def bar():

", out exception);





Jul 29, 2010 at 6:16 PM

You can also use engine.GetService<ExceptionOperations> to get a language specific exception service. This service also accepts ObjectHandles to deal with remote exception objects.