Cannot use location() within onMissingTemplate()... why?

Hi, there!

I was trying to use onMissingTemplate to handle “page 404” errors on my website. But when I tried to use location() to redirect the user to my custom 404 page, it doesn’t work.

This is my original code in the Application.cfc:

function onMissingTemplate(string targetPage)
{
     location(url="/error-404/", addtoken=false);
}

I also tried to use cfheader() to make it work, but it also doesn’t:

function onMissingTemplate(string targetPage)
{
     cfheader(name="Location", value="/error-404/");
     abort;
}

It seems like it’s simply ignored by lucee and the actual error is displayed on the screen.

It only WORKED when I tried onError handler instead:

function onError(struct exception, string eventName)
{
     if (exception.type EQ "missinginclude") {
          location(url="/error-404/", addtoken=false);
     }
}

Am I doing something wrong using onMissingTemplate or is it just the way it works? If it is, why?

Thanks for your help!

OS: Windows Server 2016
Java Version: 11.0.7 (AdoptOpenJDK) 64bit
Tomcat Version: Apache Tomcat/9.0.35
Lucee Version: Lucee 5.3.6.61

In particular:

To include the contents of a page in the onMissingTemplate function, use the cfinclude tag. Do not use any other method to include or redirect other page content, including tags and functions such as cflocation, GetPageContext().forward(), and GetPageContext().include().

Because:

If the onMissingTemplate function is invoked, the onApplicationStart and onSessionStart event handlers are first invoked, if appropriate, but the onRequestStart, onRequest and onRequestEnd handlers are not invoked, and processing of the request terminates when the onMissingTemplate handler returns.

HTH

– Denny

2 Likes