Castle Style Errors

time to read 2 min | 379 words

I had to compare different styles of error handling approaches, and I automatically compared the ideal, Castle Style errors, to the nasty, Mystery HRESUTL of the Week.

But what does Castle Style errors means?

Let us take a look at a few of them. When an module that was registered before the MonoRail http module had thrown an exception:

throw new Exception(
	"An exception happened on Global application or on a module that run before MonoRail's module. " + 
	"MonoRail will not be initialized and further requests are going to fail. " + 
	"Fix the cause of the error reported below.", context.Context.Error);

Or what happens when you are trying to access an ActiveRecord class when you didn't initialize it properly?

String.Format("An ActiveRecord class ({0}) was used but the framework seems not " +
   "properly initialized. Did you forget about ActiveRecordStarter.Initialize() ?",


String.Format("You have accessed an ActiveRecord class that wasn't properly initialized. " +
   "The only explanation is that the call to ActiveRecordStarter.Initialize() didn't include {0} class",

The common theme for those errors is that they are:

  • Descriptive
  • Show all the relevant information
  • Suggest a probable solution
  • Save time

I added the following exception:

throw new ActiveRecordException(String.Format(
	"You can't use [Property] on {0}.{1} because {2} is an active record class, did you mean to use BelongTo?",
	model.Property.DeclaringType.Name, model.Property.Name, propertyType.FullName));

I added that after I spent half an hour trying to figure out why something was wrong. Since then, I keep running into this exception, and then it is a "slap on the head, replace [Property] with [BelongsTo] and move on". And that is me, who wrote this bloody annoying exception that I am supposed to already know and avoid triggering. I can't imagine how many hours this exception alone has saved, just for my team.

In fact, when I gave a talk at DevTeach about MonoRail, I have literally built the entire demo by just following the instructions from the exceptions.

That is good error handling, and that is what I consider as the standard that you should aspire to. Anything less than that is cause for anger, anxiety and angst. Do save yourself the ulcer, put in the best errors you can.