I have two global controller advice classes defined as followings.
@ControllerAdvice
public class GlobalModelAttributes {
@ModelAttribut("mkey")
public String mKey() {
return "aValue";
}
}
Another class for exception handling.
@ControllerAdvice
public class GlobalExceptionHandler {
private static final String ERROR_4_XX = "error/4xx";
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler({InvalidRequestException.class}
)
public ModelAndView handleBadRequest() {
ModelAndView result = new ModelAndView(ERROR_4_XX);
result.addObject(EXCEPTION_MESSAGE, "An invalid value provided");
return result;
}
}
And in the error/4xx.html I have used the value of mkey assuming that I would get the value in the view.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<link th:rel="stylesheet" href="/css/error.css" type="text/css" />
</head>
<body>
<div class="container">
<div class="bg-container">
<h1 class="text-err">
<span th:text="${mkey}"></span>
</h1>
</div>
</div>
</body>
</html>
However, the value is not printed and I found following link(8 years old but still valid) where it is mentioned that that kind of value is not available to exception view.
https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
- Model enhancement methods (for adding additional data to the model) annotated with @ModelAttribute. Note that these attributes are not available to the exception handling views.
I believe there would be a way to get those global model attribute.
I don't want to replicate those model attributes in @ExceptionHandler as there are many of those and many of @ExceptionHandler too.