For a long time the drupal_set_message() function has been a mainstay of Drupal development. You can use this function to print a message or an error response to a user. This is useful to do as it can be done almost anywhere before the final page rendering functions and will be printed into the same area of a Drupal page.
This has recently been deprecated in Drupal 8.5.0 and so I was looking around on how to do the same thing in a new way. Drupal now has a messenger service, powered by the class Drupal\Core\Messenger\Messenger. This can be included into your code using the following shortcut.
$messenger = \Drupal::messenger();
This can be used to print messages to the user. For example, to print a standard message with a blue background do the following.
$messenger->addMessage('Message printed to a user.');
This can be done in one line like this.