spring boot 全局异常处理可以通过配置 hessianexceptionresolver 或自定义 handlerexceptionresolver 来捕获 hessian 序列化异常。具体做法是在 spring mvc 配置中注册一个实现了 handlerexceptionresolver 接口的 bean,并在其 resolveexception 方法中判断异常类型是否为 com.caucho.hessian.io.hessianprotocolexception 或其子类,如果是则返回统一的错误响应。这样做可以确保在 hessian 反序列化失败时,客户端收到标准的 json 错误信息而不是原始的堆栈跟踪。

如何配置全局异常解析器以拦截 Hessian 协议错误
通过实现 HandlerExceptionResolver 接口并设置较高的优先级,可以在请求处理链的早期捕获异常。重点在于检查异常类名是否包含 "Hessian",从而区分 HTTP 层错误和 Hessian 层错误。

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class HessianGlobalExceptionHandler implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
if (ex != null && isHessianException(ex)) {
try {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write("{\"error\":\"Hessian serialization error\",\"message\":\"" + ex.getMessage() + "\"}");
} catch (java.io.IOException e) {
e.printStackTrace();
}
return new ModelAndView();
}
return null;
}
private boolean isHessianException(Exception ex) {
String className = ex.getClass().getName();
return className.contains("Hessian") || className.contains("caucho");
}
}
如何处理 Hessian 反序列化中的字段缺失问题
当服务端发送的数据结构与客户端期望不一致时,Hessian 会抛出 StreamReadException。通过在异常解析器中专门处理此类异常,可以避免应用崩溃。关键在于识别具体的异常消息,如 "class not found" 或 "unexpected end of input",并据此调整响应内容。

import com.caucho.hessian.io.HessianProtocolException;
import com.caucho.hessian.io.StreamReadException;
// 在 resolveException 中添加更细致的判断
if (ex instanceof StreamReadException) {
// 处理字段缺失或类型不匹配
response.getWriter().write("{\"error\":\"Deserialization failed\",\"details\":\"Field mismatch or missing class\"}");
} else if (ex instanceof HessianProtocolException) {
// 处理其他协议级错误
response.getWriter().write("{\"error\":\"Protocol error\",\"details\":\"Invalid Hessian stream\"}");
}
基于 Hessian 版本兼容性导致的具体序列化失败问题
如果客户端和服务端使用的 Hessian 库版本不一致,可能会导致特定的序列化格式不被支持。例如,旧版本的 Hessian 可能不支持新的对象引用机制,从而引发 ClassCastException 或 IOException。解决此问题的方法是统一依赖版本,或在异常处理中记录详细的版本信息以便排查。


















