Jump to content

How to get 404 exception message inside template file?


abdus
 Share

Recommended Posts

While coding some templates I need to throw some Wire404Exceptions, which, expectedly, sets correct headers and renders 404 page. Since all these exceptions are extending Exception class, I can call its constructor with a message like this

<?php
$demoName = sanitizer()->pageName(input()->urlSegment1);
$demo = pages('template=demo, name=$sanitizedPagenameFrom');

if(!$demo->id) {
	throw new Wire404Exception("Demo named $demoName cannot be found, but check out its source page instead");
}

// inside template 404.php

// somehow get the error $message
echo "<h1>Page does not exist</h1>"
echo "<p>$message</p>"

What I want to do is to somehow catch this exception, or get inside 404 template the message that I set earlier in some module or another function, so that I can notify the user with a better message than "Error 404: Page not found".

There's some parts inside core that handles this sort of things but they're not utilized. 

<?php
// inside /wire/core/ProcessPageView.php

public function ___execute($internal = true) {
    // ...
    try {
	    // try to render the page
    } catch(Wire404Exception $e) {
        return $this->pageNotFound($page, $this->requestURL, false, '404 thrown during render');
    }
    // ...
}

protected function ___pageNotFound($page, $url, $triggerReady = false, $reason = '') {
	// reason is not used, or passed to 404 template
}

So, is there a way to manually catch the exception thrown? For instance, with Silex all exceptions can be intercepted using

<?php
$app = new Silex\Application();
$app->error(function (\Exception $e, $code) {
    exit('asd');
});

 

Link to comment
Share on other sites

Huh, turns out there's this method inside ProcessPageView class

<?php
// /wire/core/ProcessPageView.php
	/**
	 * Hook called when the pageview failed to finish due to an exception.
	 *
	 * Sends a copy of the exception that occurred.
	 *
 	 */
	public function ___failed(\Exception $e) {
		$this->wire()->setStatus(ProcessWire::statusFailed);
	}

which I should be able to hook and access the exception and message with

<?php
wire()->addHookBefore('ProcessPageView::failed', function(HookEvent $e) {
	$ex = $e->arguments(0);
	$message = $ex->getMessage();
})

But, it's not firing when hooked inside /site/ready.php. In fact it does not appear to be used anywhere inside the core at all.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...