This example installs an error handler to a parser. The error handler logs error messages to a logger (see e385 The Quintessential Logging Program).
// Create a builder
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
// Set an error listener
builder.setErrorHandler(new MyErrorHandler());
// Use the builder to parse the file
Document doc = builder.parse(new File("infilename.xml"));
} catch (SAXException e) {
// A parsing error occurred; the xml input is not valid.
// This exception can still be thrown, even if an error handler is installed.
} catch (ParserConfigurationException e) {
} catch (IOException e) {
}
// This error handler uses a Logger to log error messages
class MyErrorHandler implements ErrorHandler {
// This method is called in the event of a recoverable error
public void error(SAXParseException e) {
log(Level.SEVERE, "Error", e);
}
// This method is called in the event of a non-recoverable error
public void fatalError(SAXParseException e) {
log(Level.SEVERE, "Fatal Error", e);
}
// This method is called in the event of a warning
public void warning(SAXParseException e) {
log(Level.WARNING, "Warning", e);
}
// Get logger to log errors
private Logger logger = Logger.getLogger("com.mycompany");
// Dump a log record to a logger
private void log(Level level, String message, SAXParseException e) {
// Get details
int line = e.getLineNumber();
int col = e.getColumnNumber();
String publicId = e.getPublicId();
String systemId = e.getSystemId();
// Append details to message
message = message + ": " + e.getMessage() + ": line="
+ line + ", col=" + col + ", PUBLIC="
+ publicId + ", SYSTEM=" + systemId;
// Log the message
logger.log(level, message);
}
}
Given the following input file, MyErrorHandler.fatalError() is called and parse() throws a SAXParseException as well.