Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent XML parsing errors being written to System.err (stderr)?

Tags:

I am writing some unit tests that are deliberately passing bad strings to the Java DOM XML parser.

E.g.

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder();  String message_xml = ""; // Empty string, not valid XML!!! ByteArrayInputStream input = new ByteArrayInputStream(message_xml.getBytes()); Document doc = db.parse(input); 

This is correctly throwing a SAXParseException (which is what my unit test expects). But it is also writing a message to System.err (stderr) in the Java console:

[Fatal Error] :1:1: Premature end of file. 

Is there any way to configure the XML parser to NOT write to stderr?

I'm using Java 1.6SE.

like image 991
jfritz42 Avatar asked Oct 07 '11 18:10

jfritz42


1 Answers

Install your own ErrorHandler:

db.setErrorHandler(new ErrorHandler() {     @Override     public void warning(SAXParseException e) throws SAXException {         ;     }      @Override     public void fatalError(SAXParseException e) throws SAXException {         throw e;     }      @Override     public void error(SAXParseException e) throws SAXException {         throw e;     } }); 
like image 139
phihag Avatar answered Oct 27 '22 00:10

phihag