【发布时间】:2020-07-10 10:36:26
【问题描述】:
我知道这已经被问过了。我需要开发用户定义的异常处理以及属性类,但我没有检索新添加的属性(DSMException.cs 属性)异常。我经历了这两个解决方案-
Custom exception with properties
What is the correct way to make a custom .NET Exception serializable?
我有一个Property 类-DSMException,其中包含三个属性Type、Message、InnerExceptionMessage,需要显示。
DSMException.cs
public class DSMException
{
public string Type { get; set; }
public string Message { get; set; }
public string InnerExceptionMessage { get; set; }
}
给出了相应的自定义异常类。
FatalException.cs
public class FatalException :Exception
{
DSMException exception = new DSMException();
public FatalException():base()
{
}
public FatalException(string? Message): base(Message)
{
exception.Type = "FATAL";
exception.Message = "MESSAGE:" + Message;
}
public FatalException(string? Message,Exception ex) : base(Message,ex)
{
exception.Type = "FATAL";
exception.Message = "MESSAGE: " + ex.Message;
exception.InnerExceptionMessage = "MORE DET: " + ex.ToInnerMostException().Message;
}
}
我正在抛出如下代码的异常 Channel.cs
public override void Run(ServiceSettings settings, DataSource dataSource, string path)
{
try
{
var channel = entities.Channels
.Where(c => c.Name == parameters.Channel)
.FirstOrDefault();
if (channel != null)
{
// ANY LOGIC
}
else
{
throw new FatalException("Invalid Channel Name !!!");
}
}
catch (FatalException ex)// for channel is null
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
在捕获 Exceptions-FatalExceptions 期间此处引发错误
FolderInvocation.cs(错误)
private void DoFolderInvocation(DataSource dataSource, Plugin plugin)
{
// Do type invocation
try
{
result = helper.Invoke(importableFile.Path);// This invokes the Run method, I skipped those codes
if (result == null)
logger.WriteError($"{dataSource.Key}: Unknown error while processing file '{importableFile.Path}'.");
else if (result.Success == false)
logger.WriteError($"{dataSource.Key}: Error while processing file '{importableFile.Path}'.
{result.Message}");
else
logger.WriteDebug($"{dataSource.Key}: File '{importableFile.Path}' was processed successfully.
{result.Message}");
}
catch (FatalException exFatal)// **Problem Arises here-> need to get Ex.Type in the FatalException**
{
logger.WriteError($"{dataSource.Key}: An error occurred while processing data source:
{exFatal.Message}");
throw exFatal;
}
catch (Exception ex)
{
logger.WriteError($"{dataSource.Key}: Invocation error while processing file '{importableFile.Path}'.
{ex.Message}");
}
}
我所缺少的,就这些最小复制代码而言是正确的,但我需要在 FatalException 中获取 Ex.Type。请给我建议。
【问题讨论】:
-
这里出现什么问题?能否请您添加错误文本?
-
您的
DSMException exception是私人的。不能在FatalException的实例之外访问,它是字段,不是属性。