5

The code I am working on has a bunch of TRY/CATCH blocks in Template::Toolkit templates. They look like this:

[% TRY; x = OBJ.method(data); CATCH; "<!-- error: $error -->"; END %]

This is bad from two perspectives. First, the error is being inserted into the HTML handed to the user, and second, the error is hard to find for the developers. In my opinion, all errors should be logged to the same error log. Right now I do that through the warn function. I have changed the code above to be

[% TRY %]
    [% x = OBJ.foo(data) %]
[% CATCH %]
    [% RAWPERL %]
        warn "error calling method foo on a bar object: " . $stash->get("error");
    [% END %]
[% END %]

but this feels far too verbose for what should be a simple thing. Is there some better way I am ignorant of to do this?

Chas. Owens
  • 64,182
  • 22
  • 135
  • 226
  • Do you have to do this in the template? I think such (relatively) complex constructs belong in the code that prepares the data to be displayed (i.e. the controller, if we use MVC terms), not in the template itself. – Michał Wojciechowski Sep 13 '11 at 14:52
  • @Michal I completely agree with you in principle, but that assumes the code is in an MVC framework. Sadly this is nasty legacy code. There is no controller class. – Chas. Owens Sep 13 '11 at 15:24
  • 1
    I'd still try introducing as much separation between business logic and presentation as possible, like doing most of the work in a single `[% RAWPERL %]` block at the very beginning of the template, before any content gets rendered. – Michał Wojciechowski Sep 13 '11 at 15:48

1 Answers1

8

Great idea! Never thought of it myself, but will implement the solution for my own system now.

And it is possible out of the box! The stderr filter prints output of a block to STDERR:

[% FILTER stderr %]  
   Found a big problem
[% END %]

No MVC required, no code, just a better life.

A more advanced way to do it is to create an object within your controller whose job it is to log errors, so it can process them more intelligently:

[% logger.warn('Big Problem') %]

It could email them, put them into the log, or SMS to the developer you don't like. ;-)

KateYoak
  • 1,591
  • 3
  • 18
  • 34