Not sure if this is what you are looking for, but I'm giving it a shot.
You can retrieve the messages like this:
$messages = $this->messageManager->getMessages(true);
where messageManager
is an instance of \Magento\Framework\Message\ManagerInterface
.
In the core, this is used for ajax calls in order to return the error messages in the json response like this (\Magento\Catalog\Controller\Adminhtml\Category\Move
):
$block = $this->layoutFactory->create()->getMessagesBlock();
...
$block->setMessages($this->messageManager->getMessages(true));
$resultJson = $this->resultJsonFactory->create();
return $resultJson->setData([
'messages' => $block->getGroupedHtml(),
'error' => $error
]);
For actions with output you shouldn't do anything (I think). The default.xml
layout file from the Magento_Theme
module already contains this block <block class="Magento\Framework\View\Element\Messages" name="messages" as="messages" template="Magento_Theme::messages.phtml"/>
that should handle the messages.
[Side note]:
Don't use $this->_objectManager->get('Magento\Framework\Escaper')->escapeHtml($message)
. Inject in your constructor an instance of Magento\Framework\Escaper
and use that.