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:
InfoException.java
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.
UserService.java
public List<EasyUser> searchUser(String searchString) {
List<EasyUser> easyUsers = easyUserList.stream().filter(
it -> it.uuid.toString().contains(searchString)
|| it.username.contains(searchString)
|| it.password.contains(
searchString)
).toList();
if (easyUsers.isEmpty()) {
throw new UserNotFoundException("No user found with the searchString: \"" + searchString + "\"");
}
return easyUsers;
}
LayoutComponent
Now we need to create a container element for the message in the LayoutComponent.
We first define a constant TOAST_CONTAINER_ID:
LayoutComponent.java
public static final String TOAST_CONTAINER_ID = "toastContainer";
We first import the TOAST_CONTAINER_ID in the LayoutComponent.jte