我在沙盒中执行了Dynamics CRM 2013插件。
此代码具有以下自定义异常类:
[Serializable]
public class PluginValidationException : Exception
{
public PluginValidationException()
{
}
protected PluginValidationException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
public PluginValidationException(string message)
: base(message)
{
}
public PluginValidationException(string message, Exception inner)
: base(message, inner)
{
}
}
在插件中引发此异常时,将导致一个通用错误窗口,日志文件中没有详细信息:
未处理的异常:System.ServiceModel.FaultException`1 [[Microsoft.Xrm.Sdk.OrganizationServiceFault,Microsoft.Xrm.Sdk,Version = 6.0.0.0,Culture = neutral,PublicKeyToken = 31bf3856ad364e35]]:System.Runtime.Serialization.SerializationException: Microsoft Dynamics CRM遇到错误。管理员或支持者的引用编号:#1355B4E4详细信息:
-2147220970
call 栈
在Microsoft.Crm.Application.Platform.ServiceCommands.PlatformCommand.XrmExecuteInternal()
在Microsoft.Crm.Application.Platform.ServiceCommands.CreateCommand.Execute()
在Microsoft.Crm.Application.Platform.EntityProxy.Create处(Boolean performDuplicateCheck,Guid auditingTransactionId)
在Microsoft.Crm.Application.Platform.EntityProxy.Create(Boolean performDuplicateCheck)
在Microsoft.Crm.Application.Platform.EntityProxy.CreateAndRetrieve(String [] columnSet, bool(boolean) performDuplicateCheck)
在Microsoft.Crm.Application.WebServices.InlineEdit.CommandBase.UpdateEntity(实体实体, bool(boolean) 值检索)
在Microsoft.Crm.Application.WebServices.InlineEdit.SaveCommand.ExecuteCommand(String commandXml)
在Microsoft.Crm.Application.WebServices.InlineEdit.CommandBase.Execute(String commandXml)
System.Runtime.Serialization.SerializationException:Microsoft Dynamics CRM遇到错误。管理员或支持者的引用编号:#1355B4E4
2014-04-06T02:04:30.0972001Z
[Demo.DemoPlugin:Demo.DemoPlugin.BasicCrmPlugin]
[d86b89ab-f1bc-e311-9408-000c29254b18:Demo.DemoPlugin.BasicCrmPlugin:创建联系人)
查看CRM跟踪日志将显示以下内容:
System.Runtime.Serialization.SerializationException:程序集“Demo.DemoPlugin,版本= 1.0.0.0,区域性=中性,PublicKeyToken = fbb51ba1e588d276”中的类型“Demo.Helpers.PluginValidationException”未标记为可序列化。
在Microsoft.Crm.Sandbox.SandboxAppDomainHelper.Execute(IServiceEndpointNotificationService serviceBusService,IOrganizationServiceFactory OrganizationServiceFactory,String pluginTypeName,String pluginConfiguration,String pluginSecureConfig,IPluginExecutionContext requestContext)
在Microsoft.Crm.Sandbox.SandboxWorker.Execute(SandboxCallInfo callInfo,SandboxPluginExecutionContext requestContext,Guid pluginAssemblyId,Int32 sourceHash,字符串assemblyName,Guid pluginTypeId,字符串pluginTypeName,字符串pluginConfiguration,字符串pluginSecureConfig,SandboxRequestCounter&workerCounter)
根据一些阅读,我不认为这是一个错误-而是因为自.NET 4(我正在使用.NET 4.5)以来,自定义
Exception
类本身不受信任。有谁知道如何制作将与CRM沙箱一起使用的自定义异常类。我使用自定义异常类,是因为我捕获了错误,并且需要区分由于插件未正确注册而导致的
InvalidPluginExecutionException
异常。更新时间:2014年4月8日
这是插件中捕获异常的代码,将其放在Stackoverflow上的过程大大简化了:
try
{
//TODO: Prevalidation Logic
ValidatePluginExecution(crmContext, logging, out keyName);
//TODO: Postvalidation Logic
}
catch (PluginValidationException ex)
{
//TODO: Specific logging for Plugin Validation Exception
throw new InvalidPluginExecutionException("Did Not Validate");
}
catch (InvalidPluginExecutionException ex)
{
logging.Write("InvalidPluginExectionException at Plugin Validation");
throw;
}
catch (Exception ex)
{
logging.Write("Unhandled Exeception During Plugin Validation Operation");
logging.Write(ex);
throw new InvalidPluginExecutionException("Error. Download Log and submit to the Help Desk.", ex);
}
最佳答案
经过一些额外的测试,这是我能够确定的:
显然,只有在明确地这样做的情况下,您才可以访问堆栈跟踪以获取异常。从沙盒插件抛出异常时,只要该异常是CRM平台“知道”的异常,实际上就不会显示该异常的堆栈跟踪信息(不确定它在做什么,在这里,但是我猜到了正在查看异常的类型,并以不同的方式处理不同的类型)。如果类型未知,则会导致CRM尝试将异常序列化,这是不允许的,因为它使用反射(为什么必须序列化(不确定),这是不允许的。
这是一个示例插件,其中包含一些有效的示例,而有些无效:
public class TestPlugin: IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
try
{
OtherMethod();
}
catch (Exception ex)
{
var trace = (ITracingService)serviceProvider.GetService(typeof (ITracingService));
trace.Trace("Throwing Plugin");
// Doesn't work
throw new InvalidPluginExecutionException("Error ", ex);
}
}
// Works:
//public void Execute(IServiceProvider serviceProvider)
//{
//try
//{
//OtherMethod();
//}
//catch (Exception ex)
//{
//var trace = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
//trace.Trace("Throwing Plugin");
//throw new InvalidPluginExecutionException("Error " + ex);
//}
//}
// Doesn't Work:
//public void Execute(IServiceProvider serviceProvider)
//{
// try
// {
// OtherMethod();
// }
// catch (Exception ex)
// {
// throw;
// }
//}
// Doesn't Work:
//public void Execute(IServiceProvider serviceProvider)
//{
// try
// {
// OtherMethod();
// }
// catch (Exception ex)
// {
// throw new InvalidPluginExecutionException("Error", ex);
// }
//}
public void OtherMethod()
{
throw new MyException();
}
}
public class MyException : Exception
{
}
因此,回答您的问题:我编写了一个异常处理程序,以便能够遍历内部异常并确定是否有效:
/// <summary>
/// Exception Handler For Exceptions when executing in Sandbox Isolation Mode
/// </summary>
public class ExceptionHandler
{
/// <summary>
/// Determines whether the given exception can be thrown in sandbox mode.
/// Throws a Safe if it can't
/// </summary>
/// <param name="ex">The ex.</param>
/// <returns></returns>
/// <exception cref="InvalidPluginExecutionException"></exception>
/// <exception cref="Exception"></exception>
public static bool CanThrow(Exception ex)
{
var exceptionRootTypeIsValid = IsValidToBeThrown(ex);
var canThrow = exceptionRootTypeIsValid;
var innerException = ex.InnerException;
// While the Exception Types are still valid to be thrown, loop through all inner exceptions, checking for validity
while (canThrow && innerException != null)
{
if (IsValidToBeThrown(ex))
{
innerException = innerException.InnerException;
}
else
{
canThrow = false;
}
}
if (canThrow)
{
return true;
}
var exceptionMessage = ex.Message +
(ex.InnerException == null
? string.Empty
: " Inner Exception: " + ex.InnerException.ToStringWithCallStack());
// ReSharper disable once InvertIf - I like it better this way
if (exceptionRootTypeIsValid)
{
// Attempt to throw the exact Exception Type, with the
var ctor = ex.GetType().GetConstructor(new[] { typeof(string) });
if (ctor != null)
{
throw (Exception) ctor.Invoke(new object[] { exceptionMessage });
}
}
throw new Exception(exceptionMessage);
}
/// <summary>
/// Determines whether the specified ex is valid to be thrown.
/// Current best guess is that it is not
/// </summary>
/// <param name="ex">The ex.</param>
/// <returns></returns>
private static bool IsValidToBeThrown(Exception ex)
{
var assembly = ex.GetType().Assembly.FullName.ToLower();
return assembly.StartsWith("mscorlib,") || assembly.StartsWith("microsoft.xrm.sdk,");
}
}
可以从您插件的最高尝试捕获中调用它,如下所示:
catch (InvalidPluginExecutionException ex)
{
context.LogException(ex);
// This error is already being thrown from the plugin, just throw
if (context.PluginExecutionContext.IsolationMode == (int) IsolationMode.Sandbox)
{
if (Sandbox.ExceptionHandler.CanThrow(ex))
{
throw;
}
}
else
{
throw;
}
}
catch (Exception ex)
{
// Unexpected Exception occurred, log exception then wrap and throw new exception
context.LogException(ex);
ex = new InvalidPluginExecutionException(ex.Message, ex);
if (context.PluginExecutionContext.IsolationMode == (int)IsolationMode.Sandbox)
{
if (Sandbox.ExceptionHandler.CanThrow(ex))
{
// ReSharper disable once PossibleIntendedRethrow - Wrap the exception in an InvalidPluginExecutionException
throw ex;
}
}
else
{
// ReSharper disable once PossibleIntendedRethrow - Wrap the exception in an InvalidPluginExecutionException
throw ex;
}
}
我相信这是一个实际的错误,并且我已经向Microsoft提出了支持请求,我们将看看他们是否同意...
更新!
我与Microsoft一起创建了一个票证:(不确定这些数字是什么意思,但是它们确实在主题中,并希望将来对某人有所帮助:REG:115122213520585 SRXCAP:1318824373ID)。他们确实确认CRM沙盒插件不支持自定义异常(exception)。
请对此Connect Ticket进行投票,以使Microsoft修复此问题或至少更好地处理它!