Lab 8: Exception Messages
One benefit of server-side rendering is leveraging server exceptions to display useful information to the user.
In this lab, we will catch Exceptions using a Spring @ControllerAdvice and show them to the user in a toast message.
Exceptions
We start by creating an InfoException base class in the de.tschuehly.easy.spring.auth.web.exception package:
package de.tschuehly.easy.spring.auth.web.exception;
public class InfoException extends RuntimeException{
public InfoException(String message) {
super(message);
}
}Then we create a UserNotFoundException that extends the InfoException in the de.tschuehly.easy.spring.auth.user package:
package de.tschuehly.easy.spring.auth.user;
import de.tschuehly.easy.spring.auth.web.exception.InfoException;
public class UserNotFoundException extends InfoException {
public UserNotFoundException(String message) {
super(message);
}
}UserService
Now we will adjust the UserService.searchUser method to throw the UserNotFoundException when no users are found.
LayoutComponent
Now we need to create a container element for the message in the LayoutComponent.
We first define a constant TOAST_CONTAINER_ID:
We first import the TOAST_CONTAINER_ID in the LayoutComponent.jte
Then we add a <div> element that has the ID set to TOAST_CONTAINER_ID after the <body> element.
MessageComponent
Now we create a MessageComponent ViewComponent in the de.tschuehly.easy.spring.auth.web.message package.
We also define an MessageType enum that has a severity method.
Now we will create the corresponding MessageComponent.jte
(1): In the template, we create an <div> element where we set the id to a timestamp, we define as a local variable with the !{var} syntax
(2): We use the <button onclick> attribute to hide the toast when the user clicks on the X
(3): We create a <h2> element in it that shows the severity and the message of the exception.
ControllerAdvice
Now we will create an ExceptionAdvice.java class in the de.tschuehly.easy.spring.auth.web.advice package:
(1): We annotate the class with the@ControllerAdvice annotation.
(2): We autowire the MessageComponent
(3): We define an @ExceptionHandler method that handles the InfoException.class
(4): We retarget the response to the <div> we created earlier with the TOAST_CONTAINER_ID
(5): We set the Swap method to INNER_HTML
Sucess!
Restart the application and navigate to http://localhost:8080.
Now search for a string not present in the data, and then you will see the toast message with the exception message.

Lab-8 Checkpoint 1
If you are stuck you can resume at this checkpoint with:
git checkout tags/lab-8-checkpoint-1 -b lab-8-c1
Last updated