How to code custom 404 error handling?
You could just use the Fast404 module (if I'm understanding your question correctly).


  Drupal has expensive 404 errors. On an 'average' site with an
  'average' module load, you can be looking at 60-100MB of memory being
  consumed on your server to deliver a 404. Consider a page with a bad
  .gif link and a missing .css file. That page will generate 2 404s
  along with the actual load of the page. You are most likely looking at
  180MB of memory to server that page rather than the 60MB it should
  take.
  
  That's where Fast 404 comes in. This module combines a very common
  method of handling missing image/file 404 errors (discussed here and
  planned for Drupal 8) with a method created by dpardo (a co-maintainer
  of this project) to deliver super fast 404 error pages for both
  missing images and bad paths. Depending on which method of
  implementation you choose (aggressive or super aggressive) you can
  deliver 404 errors using less than 1MB of memory on your server.