Lean  $LEAN_TAG$
KeyErrorPythonExceptionInterpreter.cs
1 /*
2  * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
3  * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14 */
15 
16 using System;
17 using Python.Runtime;
18 using QuantConnect.Util;
19 using System.Collections.Generic;
20 
22 {
23  /// <summary>
24  /// Interprets <see cref="KeyErrorPythonExceptionInterpreter"/> instances
25  /// </summary>
27  {
28  /// <summary>
29  /// Determines the order that an instance of this class should be called
30  /// </summary>
31  public override int Order => 0;
32 
33  /// <summary>
34  /// Determines if this interpreter should be applied to the specified exception.
35  /// </summary>
36  /// <param name="exception">The exception to check</param>
37  /// <returns>True if the exception can be interpreted, false otherwise</returns>
38  public override bool CanInterpret(Exception exception)
39  {
40  var pythonException = exception as PythonException;
41  if (pythonException == null)
42  {
43  return false;
44  }
45 
46  using (Py.GIL())
47  {
48  return base.CanInterpret(exception) &&
49  pythonException.Type.Name.Contains("KeyError", StringComparison.InvariantCultureIgnoreCase);
50  }
51  }
52  /// <summary>
53  /// Interprets the specified exception into a new exception
54  /// </summary>
55  /// <param name="exception">The exception to be interpreted</param>
56  /// <param name="innerInterpreter">An interpreter that should be applied to the inner exception.</param>
57  /// <returns>The interpreted exception</returns>
58  public override Exception Interpret(Exception exception, IExceptionInterpreter innerInterpreter)
59  {
60  var pe = (PythonException)exception;
61 
62  var key = string.Empty;
63  if (pe.Message.Contains('[', StringComparison.InvariantCulture))
64  {
65  key = pe.Message.GetStringBetweenChars('[', ']');
66  }
67  else if (pe.Message.Contains('\'', StringComparison.InvariantCulture))
68  {
69  key = pe.Message.GetStringBetweenChars('\'', '\'');
70  }
72 
73  message += PythonUtil.PythonExceptionStackParser(pe.StackTrace);
74 
75  return new KeyNotFoundException(message, pe);
76  }
77  }
78 }