@Component
public class BeetlErrorViewResolver implements ErrorViewResolver {
private static final Map<Series, String> SERIES_VIEWS;
@Value("${beetl.templatesPath:templates}")
String templatesPath;
@Value("${beetl.suffix:btl}")
String suffix;
private static ArrayList<String> errorFiles = new ArrayList<String>();
public void getErrorFiles() {
if (errorFiles.isEmpty()) {
String path = BeetlErrorViewResolver.class.getClassLoader().getResource("").getFile();
File templates = new File(path + templatesPath + "/error");
File[] files = templates.listFiles();
for (File file : files) {
if (file.isFile())
errorFiles.add(file.getName());
}
}
}
static {
Map<Series, String> views = new EnumMap<>(Series.class);
views.put(Series.CLIENT_ERROR, "4xx");
views.put(Series.SERVER_ERROR, "5xx");
SERIES_VIEWS = Collections.unmodifiableMap(views);
}
@Override
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
ModelAndView modelAndView = resolve(String.valueOf(status), model);
if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {
modelAndView = resolve(SERIES_VIEWS.get(status.series()), model);
}
return modelAndView;
}
private ModelAndView resolve(String viewName, Map<String, Object> model) {
viewName = viewName + "." + suffix;
getErrorFiles();
try {
for (String error : errorFiles) {
if (error.equals(viewName))
return new ModelAndView("/error/" + viewName, model);
}
} catch (Exception ex) {
}
return null;
}
}