我認爲自定義過濾器實際上效果最好。
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
chain.doFilter(request, response);
} catch (Throwable e) {
doCustomErrorLogging(e);
if (e instanceof IOException) {
throw (IOException) e;
} else if (e instanceof ServletException) {
throw (ServletException) e;
} else if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else {
//This should never be hit
throw new RuntimeException("Unexpected Exception", e);
}
}
}
值得指出的是,錯誤處理servlet代碼可以從'javax.servlet.error.exception'屬性中的'request'對象中檢索異常。例如:'request.getAttribute(「javax.servlet.error.exception」)' – nilskp