Episerver provides content editors with a lot of flexibility for configuring content.  Gone are the days of having lots and lots of different templates.  On my projects, I would typically have less than 20-page types and then x number of blocks.  One common problem that keeps cropping up, is how to deal with block exceptions?

On some of the more content/feature-heavy pages, I've had page instances that might have 100+ blocks loaded onto it. If one of those blocks error for whatever reason, the whole page falls over and the user is shown a 500 error.  In the majority of situations, the better solution is to have Episerver deal with the error quietly in the background and then render the page out as you expect and in most circumstances have a very small area of a page look a bit funky or not display.

Episerver is very customizable and allows you to hook into it pretty easily.  In today's guide, we're going to go over some code that will hide all exceptions thrown by blocks for you to deal with yourself.

IContentRenderer

In Episerver the IContentRenderer is the way Episerver renders partial content.  If we want to create a custom rule before we render content, we can implement this interface and then tell structure-map to use it, instead of the default implementation.

The code is very simple to implement. First, we implement IContentRenderer which has one method:

Render() is the method that you need to override in order to add the custom logic to handle exceptions. Next, we pass in the Episerver MvcContentRenderer into the constructor, found in Episerver.dll.

Lastly, we manually call the Render method and wrap it in a try/catch and that's it.  This snippet will now be called whenever we try to run a block.  If the block throws an exception for whatever reason, the try/catch will hide it and the rest of the page will load as expected. The structure map code might look similar to this in your configuration container:

One frequent point is having a whole page fall over if a single block throws an unexpected exception.  How you deal with it will largely be based on your web strategy.  One common way is to hide the exceptions and log them somewhere.

If you want to adopt this approach, you can implement your own content render.  With a bit of structure map trickery, you can ensure your class gets the call whenever a block is rendered.  All you need to do is implement the Render method however you feel fit.