spring boot 全局异常处理可以通过在 @controlleradvice 类中定义针对 saxexception、parserconfigurationexception 或 ioexception 的方法,配合 @exceptionhandler 注解来捕获 xml 解析异常。具体做法是识别这些异常类型并返回统一的错误响应,例如 json 格式的 400 或 500 状态码,从而避免默认的 whitelabel error page 暴露内部细节。

如何区分不同类型的 XML 解析异常
XML 解析异常主要分为结构错误(如 SAXException)和配置/环境错误(如 ParserConfigurationException)。开发者需要根据具体的异常子类来判断是格式问题还是环境问题,并在 @ExceptionHandler 中分别处理,以便返回更精确的错误信息。

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
@ControllerAdvice
public class GlobalXmlExceptionHandler {
@ExceptionHandler(SAXException.class)
public ResponseEntity<string> handleSaxException(SAXException ex) {
return ResponseEntity.badRequest().body("XML 格式错误: " + ex.getMessage());
}
@ExceptionHandler(ParserConfigurationException.class)
public ResponseEntity<string> handleParserConfigException(ParserConfigurationException ex) {
return ResponseEntity.status(500).body("XML 解析器配置错误: " + ex.getMessage());
}
@ExceptionHandler(IOException.class)
public ResponseEntity<string> handleIOException(IOException ex) {
return ResponseEntity.status(500).body("IO 读取错误: " + ex.getMessage());
}
}</string></string></string>
如何处理 XML 解析过程中的编码问题
当 XML 文件包含非 UTF-8 编码时,解析器通常会抛出 MalformedInputException 或 SAXParseException。开发者可以在 @ExceptionHandler 中专门捕获这些异常,并提示用户检查文件编码或转换编码后再上传,确保解析过程顺利进行。

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.xml.sax.SAXParseException;
import com.sun.org.apache.xerces.internal.impl.io.MalformedInputException;
@ControllerAdvice
public class EncodingExceptionHandler {
@ExceptionHandler(MalformedInputException.class)
public ResponseEntity<string> handleMalformedInput(MalformedInputException ex) {
return ResponseEntity.badRequest().body("编码不匹配,请检查 XML 文件编码");
}
@ExceptionHandler(SAXParseException.class)
public ResponseEntity<string> handleSaxParseError(SAXParseException ex) {
return ResponseEntity.badRequest().body("XML 解析位置错误: 行 " + ex.getLineNumber() + ", 列 " + ex.getColumnNumber());
}
}</string></string>
基于 SAXParseException 的行号定位问题
当 XML 解析失败时,SAXParseException 提供了详细的行号和列号信息。开发者可以利用这些信息在错误响应中明确指出错误发生的具体位置,帮助前端或用户上传者快速定位并修正 XML 格式问题。











