Do some custom action on a 404 or 500 document?

Hi all

I’d like to do some custom action when in production mode a 404 or 500
document is shown.

When displaying a 404 e.g. I want to check if the user has typed in the
URL manually or if he was directed there from somewhere in the website
(by exploring the headers). When the latter is the case, I’d like to
inform the webmaster somehow, maybe with an email…

How can I accomplish this?