In VbScript Err.Raise is used to "raise an error". The equivalent action in .NET is to throw an exception. While these two approaches fulfil more or less the same function, the mechanism for identifying the error/exception is different. In your VbScript example you have used the error number -1000. This can be detected in code higher up the stack with something like:
If Err.Number = -1000 Then
' Do something
End If
In .NET, instead of error numbers we use Type hierarchies. An exception object is derived from System.Exception
, and it's usual to have an exception type that specifically identifies the kind of problem which has been encountered. For more sophisticated requirements, you might make a hierarchy that allows you to catch
similar kinds of exceptions in the same handler. (For example, the Tridion CM throws exceptions that derive from Tridion.Common.TridionException) When throwing an exception from an event handler like this, you probably just need to create a suitable exception derived directly from Exception.
So for this example, you might write something like:
[Serializable]
public class InappropriatePublicationTargetException : Exception
{
public InappropriatePublicationTargetException() { }
public InappropriatePublicationTargetException(string message) : base(message) { }
public InappropriatePublicationTargetException(string message, Exception inner)
: base(message, inner) { }
protected InappropriatePublicationTargetException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
}
Which might seem like a mouthful until you learn to type
Ctrl-K-Ctrl-X v
tab ex
tab InappropriatePublicationTarget
Enter to have Visual Studio's exception snippet generate the code for you.
With a class like this available, you can write something like:
throw new InappropriatePublicationTargetException(
"This page should be published only to mobile site");
Of course, you may be asking "what's the point of this extra ritual"? Sure - in each case, what you are probably trying to achieve is having the err.Description
or Exception.Message
appear in the GUI for the end user to see. That might be enough, but in the general case, you need to consider that the event handler you are writing may just as well be triggered by code as by the GUI, in which case it can be very useful to be able to catch only your own exceptions.