25

I need to throw 404 error in module. Or may be there are any possibility to set required option for menu hook?

Muhammad Reda
  • 26,379
  • 14
  • 93
  • 105
webbear
  • 429
  • 1
  • 6
  • 12

4 Answers4

37

It is easy. These should take care of watchdog, HTTP 404 response code and other related things.

For Drupal 6 & 7

In your module's page callback, do: return drupal_not_found();

For Drupal 8

In the class::method() referred to in the _controller definition (i.e. the page callback or the method responsible for generating output for the request), do:

throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();

References

gagarine
  • 4,190
  • 2
  • 30
  • 39
AKS
  • 4,618
  • 2
  • 29
  • 48
  • 4
    For drupal 8 `throw new NotFoundHttpException();` see https://www.drupal.org/node/1616360 – rpayanm Feb 02 '15 at 17:53
  • 1
    You need the name space, `throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();` – No Sssweat Mar 19 '19 at 06:38
  • In drupal 7, calling `return drupal_not_found()` results in white screen of death. function exists, display errors enabled, nothing outputted to apache error log file. – Kiee Jan 28 '20 at 11:52
  • 1
    In Drupal 7, page callback functions wanting to report a "page not found" message should return MENU_NOT_FOUND instead of calling drupal_not_found(). – Juanmi Sosso Sep 28 '20 at 16:00
31

For Drupal 8+

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
// then
throw new NotFoundHttpException();
Muhammad Reda
  • 26,379
  • 14
  • 93
  • 105
7

MENU_NOT_FOUND should be returned in page callback functions.

Page callback functions wanting to report a "page not found" message should return MENU_NOT_FOUND instead of calling drupal_not_found(). — http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_not_found/7

Unihedron
  • 10,902
  • 13
  • 62
  • 72
cilefen
  • 387
  • 1
  • 4
  • 7
2

Look into the drupal_add_http_header() function to play with the HTTP header attributes. Also make sure you stick this at the top of your module's code to make sure it executes first. Also, you might find this helpful. https://www.drupal.org/project/generate_errors

dsteplight
  • 789
  • 7
  • 5