Passing a reason to AccessResult::forbidden in hook_node_access versus in hook_ENTITY_TYPE_access.

I am using Drupal 8.6.2 with a custom module that denies access in certain cases to viewing some nodes via hook_node_access, and to downloading some private files via hook_ENTITY_TYPE_access (implemented as hook_file_access).  This custom module appears to be working – access is allowed or denied properly. 

An enhancement to the module was to detect when this module has denied access, and if so to redirect users to a message and login form.  One approach I looked into was to use an EventSubscriber to find when an AccessDeniedHttpException occurs, and to see if it was this custom module which had caused it.  To do that, I took advantage of a “reason” parameter which can be passed to AccessResult::forbidden, and can then be tested via Exception::getMessage.  This reason is a text string, and appears to be designed for this kind of simple tagging.  I can successfully set and get the message when passed from hook_node_access, but cannot get the message when it is passed from hook_ENTITY_TYPE_access.

Please see this simple, stripped down demo implementation which illustrates this issue.  This sample module when enabled will deny access to viewing all nodes and the download of all private files on the website (Note that user #1 is unaffected).  When access is denied, a message will be shown indicating the result of calling getMessage on the Exception.  For hook_node_access it should be “Reason One” which it is, and for hook_ENTITY_TYPE_access it should be “Reason Two” but it’s empty.

Am I properly using hook_ENTITY_TYPE_access?  It does successfully grant or deny private file download access, but the failure to set a message via AccessResult::forbidden has me concerned.


Drupal version: