私はベース "例外ハンドラ"のようなものを作ろうとしています。したがって、この基本クラスは、派生クラス内の任意の数のパラメータを持つ任意のメソッドが呼び出されると、を試行します。私はここで、言葉でこれを記述する際によくないよシナリオです:キャッチ派生クラス異なるメソッドと引数を持つ基本クラスの例外
public abstract BaseClass
{
Exception _ex;
public Exception LastKnownException
{
get
{
return this._ex;
}
}
//...
//what do I do here to assign the value of above property when some random exception occur in derived class?
//...
//The closest I can get...
public void RunMethod(Action method)
{
try
{
method.Invoke();
}
catch (Exception ex)
{
this._ex = ex;
}
}
}
public class DerivedClass : BaseClass
{
public void DoRandomMethod(int couldBeOfAnyTypeHere, bool andIndefiniteNumberOfThese)
{
bool result = false;
var someObject = new OtherClass(couldBeOfAnyTypeHere, out andIndefiniteNumberOfThese);
someObject.DoInternalWork(result); // <-- here is where I need the base class to take care if any exception should occur
}
public int AnotherMethod(int? id)
{
if (!id.HasValue)
id = Convert.ToInt32(Session["client_id"]);
var someOtherObject = new OtherClassB(id.Value);
return someOtherObject.CheckSomething(); // <-- and catch possible exceptions for this one too
}
//The closest I can get... (see base class implementation)
public List<RandomClass> GetSomeListBy(int id)
{
RunMethod(() =>
string[] whateverArgs = new[] { "is", "this", "even", "possible?" };
YetAnotherStaticClass.GetInstance().ExecuteErrorProneMethod(whateverArgs); // <-- Then when something breaks here, the LastKnownException will have something
);
}
}
public class TransactionController : Controller
{
public ActionResult ShowSomething()
{
var dc = new DerivedClass();
dc.DoRandomMethod(30, true);
if (dc.LastKnownException != null)
{
//optionally do something here
return RedirectToAction("BadRequest", "Error", new { ex = dc.LastKnownException });
}
else
{
return View();
}
}
}
EDIT:私の単純なアプローチは動作しますが、唯一、私はこのラムダとのすべてのメソッドをラップする必要がありますする必要はありません-driven RunMethod()
メソッドは常にあります - 何らかの着信例外を傍受し、エラーをスローせずにException
オブジェクトを派生クラスに戻すために基本クラスが必要です。
任意のアイデアをいただければ幸いです。そして、事前に感謝!
あなたのご質問はありますか? – Ouarzy