2011-10-28 10 views
6

मेरे पास एक सामान्य वर्ग है जो टी:क्या ऐसा अपवाद पकड़ना संभव है जिसे आप संभाल नहीं सकते (सी # में)?

 
    public abstract class ErrorHandlingOperationInterceptor<T> : OperationInterceptor where T : ApiException 
    { 
     private readonly Func<OperationResult> _resultFactory; 

     protected ErrorHandlingOperationInterceptor(Func<OperationResult> resultFactory) 
     { 
      _resultFactory = resultFactory; 
     } 

     public override Func<IEnumerable<OutputMember>> RewriteOperation(Func<IEnumerable<OutputMember>> operationBuilder) 
     { 
      return() => 
      { 
       try 
       { 
        return operationBuilder(); 
       } 
       catch (T ex) 
       { 
        var operationResult = _resultFactory(); 
        operationResult.ResponseResource = new ApiErrorResource { Exception = ex }; 
        return operationResult.AsOutput(); 
       } 
      }; 
     } 
    } 

के अपवादों को पकड़ता है विशिष्ट अपवादों के लिए उप-वर्गों के साथ उदा।

 
    public class BadRequestOperationInterceptor : ErrorHandlingOperationInterceptor<BadRequestException> 
    { 
     public BadRequestOperationInterceptor() : base(() => new OperationResult.BadRequest()) { } 
    } 

यह सब पूरी तरह से काम करने लगता है। लेकिन, किसी भी तरह, लॉग में (एक बार, हर बार नहीं) एक अवैध कैस्ट अपवाद है:

 
System.InvalidCastException: Unable to cast object of type 'ErrorHandling.Exceptions.ApiException' to type 'ErrorHandling.Exceptions.UnexpectedInternalServerErrorException'. 
    at OperationModel.Interceptors.ErrorHandlingOperationInterceptor`1.c__DisplayClass2.b__1() in c:\BuildAgent\work\da77ba20595a9d4\src\OperationModel\Interceptors\ErrorHandlingOperationInterceptor.cs:line 28 

रेखा 28 पकड़ है।

मुझे क्या याद आ रही है? क्या मैंने वास्तव में कुछ गूंगा किया है?

+7

ठीक है, वहाँ हमेशा है 'TruthException', क्योंकि आप को संभाल नहीं सकता यह –

+0

कौन सा कोड में लाइन लाइन 28 है? –

+0

@ किरेन जॉनस्टोन, आपने मेरी टिप्पणी चुरा ली !! –

उत्तर

3

के रूप में लोहार ने कहा, अपने T प्रकार ApiErrorResource की है। अपने एक Exception कि ApiErrorResource से प्राप्त नहीं है के साथ ErrorHandlingOperationInterceptor आप कर रहे हैं, कुछ अपने कोड में जहां, बनाने के प्रयास में।

try 
{ 
// throw Exception of some sort 
} 
catch (BadRequestException ex) 
{ 
    BadRequestOperationInterceptor broi = new BadRequestOperationInterceptor(); 
} 
catch (Exception ex) 
{ 
    // this is NOT right 
    BadRequestOperationInterceptor broi = new BadRequestOperationInterceptor(); 
} 
+1

दरअसल मुझे विश्वास है कि यह 'एपीएक्सप्शन' टाइप है। – TrueWill

+0

मुझे समझ में नहीं आता कि यह सवाल का जवाब कैसे देता है। टाइप सिस्टम को उस समस्या की अनुमति नहीं देनी चाहिए जो मुझे लगता है कि आप प्रदर्शन करने की कोशिश कर रहे हैं - सामान्य बाधा नोट करें जहां टी: अपीएक्सप्शन '। ओपी का कोड कोई कास्टिंग नहीं कर रहा है - एक 'अवैध कैस्ट अपवाद' परिणाम कैसे हो सकता है? –

+0

मुझे लगता है कि मुझे "कुछ कोड जहां आपके कोड में ईएलएसई" कहा जाना चाहिए था। –

संबंधित मुद्दे