问题描述
我正在尝试使用Mustache为Spring MVC设计一个常见的错误页面。 我可以使用变量“错误”打印出异常类型(例如:内部服务器错误),并使用变量“消息”打印出异常消息。
我的样本胡子模板:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Common Error</title>
<h2>Unexpected Error: </h2>
<h3>Error: {{error}}</h3>
<h3>Message: {{message}}</h3>
</head>
<body>
</body>
</html>
显示为:
Unexpected Error:
Error: Internal Server Error
Message: Unexpected Runtime Error Message
问题1 :如何打印出异常Stacktrace?
问题2 :有没有一种方法可以打印胡子模板可用的所有模型变量?
1楼
而不是在Moustache Template引擎层解决此问题。 我回过头来让Spring MVC为Mustache Error View正确设置了模型。
我通过使用@ControllerAdvice
和@ExceptionHandler
做到了这@ExceptionHandler
。
我的带有所有异常处理程序的Controller Advice如下所示:
@ControllerAdvice
public class ExceptionControllerAdvice {
@ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
@ExceptionHandler(Throwable.class)
public ModelAndView genericExceptionHandler(Exception ex){
String errorMessage = getMessage(ex);
String errorRootCauseMessage = getRootCauseMessage(ex);
String errorStacktrace = getStackTrace(ex);
ModelAndView mv = new ModelAndView("errors/error");
Map<String, Object> model = mv.getModelMap();
model.put("errorMessage", errorMessage);
model.put("rootCauseErrorMessage", errorRootCauseMessage);
model.put("stackTrace", errorStacktrace);
return mv;
}
}
然后我的小胡子模板如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Generic Error</title>
<h3>Wahooo!!! You broke us! Well done. We will take a look at it and try to fix the issue.</h3>
<h4>What Happend?</h4><h5> {{errorMessage}}<h5>
<h4>What was the root cause? </h4><h5>{{rootCauseErrorMessage}}</h5>
<h4>Stacktrace:</h4>
<h6>{{stackTrace}}</h6>
</head>
<body>
</body>
</html>
这解决了我的问题。