我正在開發一個類別庫,它使用 aForm來捕獲特定WndProc訊息并在之后處理它們。處理包括檔案操作。然后,庫將處理后的值發布為公共屬性或事件。
問題:當處理拋出例外時我該怎么辦?
如果我讓它冒泡給呼叫者,它需要在哪里捕獲?因為它不是需要呼叫的函式/方法。
圖書館類:
public event EventHandler<CmmStateChangedEventArgs> CmmStateChanged;
public event EventHandler<MeasurementInfoEventArgs> MeasurementInfoChanged;
public event EventHandler<MeasurementPlanInfoEventArgs> MeasurementPlanInfoChanged;
public MeasurementPlanInfo MeasurementPlanInfo { get; private set; }
public MeasurementInfo MeasurementInfo { get; private set; }
public Status CMMStatus { get; private set; }
// event handler for internal form WndProc event
// _messageForm is a empty invisible form which catches specific WndProc messages and invokes a event if necessary
private async void _messageForm_CMMStateChanged(object sender, CmmStateChangedEventArgs e)
{
// this could throw
var command = await _stateManager.GetCommandFileAsync(Configuration.CMMObserverFolderPath);
var observer = await _stateManager.GetObserverFileAsync(Configuration.CMMObserverFolderPath);
var measInfo = new MeasurementInfo();
switch (e.Status)
{
case Status.Running:
if (command.state == "set_cnc_start")
{
// this could throw if observer is null
measInfo = new MeasurementInfo()
{
MeasurementPlanId = observer.planid,
ControllerType = observer.controllertyp,
DeviceGroup = observer.devicegroup,
FirmwareRevision = observer.firmWareRevision,
OperatorId = observer.operid,
PartNumber = observer.partnbinc,
MeasurementPlanFileName = command.planPath,
};
MeasurementInfo = measInfo;
MeasurementInfoChanged?.Invoke(this, new MeasurementInfoEventArgs() { MeasurementInfo = measInfo });
}
break;
case Status.Finished:
measInfo = new MeasurementInfo()
{
MeasurementPlanId = observer.planid,
ControllerType = observer.controllertyp,
DeviceGroup = observer.devicegroup,
FirmwareRevision = observer.firmWareRevision,
OperatorId = observer.operid,
PartNumber = observer.partnbinc,
ChrFilePath = command.chrPath,
HdrFilePath = command.hdrPath,
FetFilePath = command.fetPath
};
MeasurementInfo = measInfo;
MeasurementInfoChanged?.Invoke(this, new MeasurementInfoEventArgs() { MeasurementInfo = measInfo });
break;
case Status.Paused:
case Status.Stopped:
case Status.Exception:
default:
break;
}
CMMStatus = e.Status;
CmmStateChanged?.Invoke(this, new CmmStateChangedEventArgs() { Status = e.Status });
}
呼叫類:
public MainForm()
{
InitializeComponent();
apiConfiguration = new ApiConfiguration();
// where catch possible exception ?
api = new Calypso()
.Configure(apiConfiguration)
.Initialize();
api.CmmStateChanged = Api_CmmStateChanged;
api.MeasurementInfoChanged = Api_MeasurementInfoChanged;
api.MeasurementPlanInfoChanged = Api_MeasurementPlanInfoChanged;
}
uj5u.com熱心網友回復:
這取決于。哪個范圍可以解釋例外并采取行動(API 或呼叫者)?正在拋出什么?拋出例外是否意味著呼叫者的狀態現在不同步并且事情即將變得更糟?API 能否嘗試解決此類問題?下一個作業更改事件是否會讓呼叫者完全恢復?呼叫者是否可能對這些“周期性故障(?)”感興趣 - 可能會添加一條訊息錯過的事件。
如果例外是嚴重失敗,問題是在呼叫者中的哪里處理這個問題:我建議捕獲例外并添加失敗事件,然后呼叫者可以做出最好的回應。或者,初始化可以接受要呼叫的回呼操作。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/366162.html
