Skip to main content

Let's build an error handling aspect: part 3

April 02, 2014 mgroves 0 Comments
Tags: postsharp LetsBuildAnAspect

In the previous post, we got the aspect to communicate with the service object by using args.Instance. But it only really works for one service: TerritoryService.

How can we get it to work with other services?

One approach would be to add a bunch of casts and if-statements:

I don't like that approach much. Another approach would be to create a base class that all our service classes would inherit from. I generally try to avoid this approach as much as possible, but I think it makes sense in this case. We could create an interface, like IHasValidationCallback, but let's take it one step further and create an abstract base class that already contains the implementation.

Now that the TerritorySerivce (and our other services) have a ServiceBase base class, we can update the aspect to use ServiceBase.

And there you have it: as long as all the services in the namespace inherit from ServiceBase, this will work.

So I think we're making progress, but let's review the issues from last time:

  • This only works for ITerritoryService--what about the other services? We just addressed this one.
  • Swallowing exceptions: we should at least be logging the exception, not just ignoring it.
  • If the method has a return type, then it's returning null. If it's meant to return a reference type, that's probably fine, but what if it's returning a value type?
  • What if it's returning a collection, and the UI assumes that it will get an empty collection instead of a null reference?
  • Do we really want to return the exception message to the user?
  • NEW ISSUE: What if I forget to use ServiceBase as a base class on a new service?

Yep, we fixed one issue, but we really just shifted the problem to a base class that could easily be overlooked. Next time, let's see if we can get PostSharp to help us with that.


Matthew D. Groves

About the Author

Matthew D. Groves lives in Central Ohio. He works remotely, loves to code, and is a Microsoft MVP.

Latest Comments