2828 # From .method:
2929 'contextmethod' ]
3030
31+ from moretools import qualname
32+
3133from robottools .library .session .metaoptions import Meta
3234from robottools .library .keywords import KeywordsDict
3335
@@ -66,6 +68,9 @@ class ContextHandlerMeta(type):
6668 ## return type.__new__(metacls, clsname, bases, clsattrs)
6769
6870 def __init__ (cls , clsname , bases , clsattrs ):
71+ excname = cls .__name__ + 'Error'
72+ cls .ContextError = type (excname , (RuntimeError , ), {})
73+
6974 try :
7075 names = cls .contexts
7176 except AttributeError :
@@ -87,12 +92,17 @@ def switch_context(self, name):
8792 break
8893 for context in cls .contexts :
8994 if context .name == name :
95+ if switch_func : # Custom switch hook
96+ try :
97+ switch_func (self , name )
98+ except Exception as exc :
99+ raise cls .ContextError (
100+ "Couldn't switch context to %s (%s: %s)"
101+ % (repr (name ), qualname (type (exc )), exc ))
90102 self .contexts .remove (current )
91103 self .contexts .append (context )
92- if switch_func : # Custom switch hook
93- switch_func (self , name )
94104 return
95- raise ValueError ( name )
105+ raise cls . ContextError ( "Context not found: %s" % repr ( name ) )
96106
97107 keyword_name = switch_context .__name__ = 'switch_' + clsname .lower ()
98108 cls .keywords [keyword_name ] = switch_context
0 commit comments