拦截器里MDC.put后,异常了,怎么保证MDC.clear
时间: 2024-05-14 21:14:06 浏览: 111
MDC1200解碼器(研究用).zip
在拦截器中,可以使用try-catch-finally块来确保MDC.clear()在任何情况下都会被调用。在try块中设置MDC,然后在finally块中调用MDC.clear()。这样可以确保即使发生异常,MDC也会被清除。以下是示例代码:
```
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
MDC.put("requestId", UUID.randomUUID().toString());
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
try {
// do something
} catch (Exception e) {
// handle exception
} finally {
MDC.clear();
}
}
}
```
阅读全文