Skip to main content

Posts tagged with 'postsharp'

The Boise .NET User Group was kind enough to invite me to be a presenter. Boise is a bit too far away for me to make it there on a weekday on a small budget, but they were accomodating enough to allow me to present remotely. There were a couple minor technical issues, but mostly it went well. Even though I've done this presentation a lot, Brian cajoled me into talking about INotifyPropertyChanged, which is something I've only done once before during this talk (usually I'm constrained for time, or the group isn't interested in the MVVM pattern).

Brian Lagunas even made a recording of the presentation. The recording started a minute or so late, and it ending a couple minutes too early (the internet in the Boise location went down), but most of it is was recorded with Microsoft Live Meeting (not my favorite remote collaboration tool, but it was adequate). And now, it's on YouTube:

Slides and code are available in the AOP For You and Me GitHub repository.

In the last post, I added some compile time validation to make sure that the aspect is being used in the correct places. Today, we're going to look at actually logging the exception.

Remember early on when I said that this aspect is not generally applicable? For this part, it's especially true, since I'll be using a specific logging library + service: Exceptionless.

The application that I'm working on is meant to be deployed to an Azure web site. Because of this, I have to think a little differently about logging. You can still log to the file system, of course, but on a cloud service that may not be the best idea. You could log to table storage on Azure Storage. You could also log to a normal database. However, I wanted to use something that: a) requires very little work, b) provides some useful monitoring tools that I don't have to build, c) is very low cost or free. So, based on my research and an endorsement from Mark Greenway, I decided to explore Exceptionless.

Using Exceptionless is as simple as installing a NuGet package, pasting in your API key, and then using an extension method.

Here's how I could use Exceptionless in my aspect:

This is very similar to what I did initially, but since this project is in development, I made a few adjustments along the way to make my life easier.

SQL exceptions. Especially during development, it's very likely that I'll screw up a SQL query, forget to run a migration script, etc. Additionally, since I'm using constraints in my database, I want to handle the case where a user is trying to delete an entity and a constraint is preventing them. So I modified the aspect some more:

The way I'm checking for "constraint" exceptions feels very hacky to me, but I haven't found a better way yet.

NotImplementedException. Again, since I'm still in active development, often times a NotImplementedException will pop up. For these exceptions, I want them to crash right away, and I also don't need to worry about logging.

Now that SQL exceptions and not-implemented exceptions are handled on their own, any other exception is one that I still want to log and output to the UI in a friendly, non-yellow screen way. During development, I definitely want to see the full exception message, but that's something that will definitely need to be revisited before going into production. Back to the list:

  • This only works for ITerritoryService
  • Swallowing exceptions: we should at least be logging the exception, not just ignoring it. <- We are now logging exceptions!
  • 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? <- We'll revisit this later.
  • What if I forget to use ServiceBase as a base class on a new service?

 

In the last post, we started using ServiceBase as a way to more generally address the services and use the callback to report errors to the UI.

What happens if I put the aspect on a method in a class that doesn't inherit from ServiceBase (because either I forgot, or I put an aspect on a class outside of the service layer by mistake)? Exceptions will be swallowed, not reported, and probably cause issues elsewhere in the project.

One approach would be to change the case from "args.Instance as ServiceBase" to "(ServiceBase)args.Instance". At least then, I'll get a runtime error about casting (but only if there's an exception). With PostSharp, we can do better than that.

In fact, remember when I said that PostSharp aspects have to be marked as [Serializable]? This is because, as compile time, PostSharp instantiates those aspect objects and serializes them to be used later at runtime. BUT, since the aspect is being instantiated anyway, PostSharp also does a couple of other optional steps: it can do some compile-time initialization (to avoid runtime reflection, for instance), and it can do some compile-time validation.

That's right, we can put some code in the aspect that can check to make sure that we're applying the aspect correctly. If we aren't, it will give us a compile-time error. We could check, for instance, that the aspect is being applied to a method in a class that inherits ServiceBase.

This code will only be executed at compile-time. If the declaring type (the class that the method is in) does not inherit from ServiceBase, then PostSharp will write out an error at compile time:

Compile-time initialization error in Visual Studio 2013

So now if I ever forget to use ServiceBase, or I use this aspect in the wrong place, I'll know right when I'm compiling. And because of this validation, I can also confidently change the cast from "args.Instance as ServiceBase" to "(ServiceBase)args.Instance", knowing that if the project compiles, that cast will never fail.

How are we doing:

  • This only works for ITerritoryService--what about the other services?
  • 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?
  • What if I forget to use ServiceBase as a base class on a new service? <- We just took care of this

Next time we'll look at actually logging the exception.

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.

In the last post, I laid out the bare essentials of an error handling aspect for my service layer.

Before I proceed further with the aspect, let's examine the layer right above the service layer: the UI layer. I'm using ASP.NET MVC.

With ASP.NET MVC, there is a concept of ModelState, which holds information about validations performed during model binding, and is also used by the controller to convey error information to the view (through the Html.ValidationSummary helper, for instance). I'm already using ModelState to convey simple validation errors; I'd like to use it to convey any errors that the service layer might encounter. There are many ways to approach this; I've chosen the "callback" approach--passing a lambda to the service layer in order to communicate error information from the service layer up to the UI layer. Here's the basics:

Dependency injection gives me an object that implements the ITerritoryService interface, but I have to take one more step and pass that service the lambda x => ModelState.AddModelError("", x) in the controller instructor. This is because ModelState doesn't actually get instantiated until the controller does (so I can't pass it to the service object any sooner).

Now, when there's an exception in Territory service, I can simply use this "callback" to add an error to the ModelState. (Side note: a benefit to this approach is that it does not couple TerritoryService to my UI: if I wanted to use this service with another UI--say, WebAPI or WebForms--then I would simply have to pass in a different lambda).

Let's get the aspect to use that callback.

By using args.Instance, we can get a reference to the object in which the method resides. If that object can be cast to ITerritoryService, then we can simply call AddModelError. This works great: now anytime there's an exception in TerritoryService, it will be added as an error to ModelState and displayed to the user.

But clearly there are still issues here:

  • This only works for ITerritoryService--what about the other services?
  • 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 show the exception message to the user?

Next time, we'll start addressing the first issue, and figure out a way to make this aspect more generic.

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

Twitter