Sam
Sam

Reputation: 61

Prevent code from throwing XML exception

In the following piece of code :

try{
....
}

    catch(Exception e)
    {
            logger.error("Exception caught in method: \n");
            logger.error(e.getMessage());
            String fault = "<Fault><FaultCode>" + e.getClass().getName() + "</FaultCode><FaultDescription>" + e.getMessage() + "</FaultDescription></Fault>";
            return XmlObject.Factory.parse(fault);
    }

, is there a way to convert the "fault" string to an XML object using a code that wouldn't throw any exception or require any exception handling?

Basically, we need to return an XML object in both success and fauilure scenarios, without the method using any throws clause. That's the reason, we've removed all the specific Exception cases, that could occur in the main flow, like ParserConfiguration, IOExceptoin, XmlException etc. from the catch and kept a generic one and hard coded a string that would gather the required fault info and pass back as an XML object. But, even with this minimal coding, there is a chance of an XmlException occuring in the parse() method. Any other way, like reading from an errorConfig file or creating a separate XML object would bring in more exceptions to be handled.

So, just want to know whether its even possible to develop such a code, i.e. an exception-free catch block returning XML? Or, if anyone could recommend any other approach would also be fine.

FYI : The main code basically transforms an XML or enriches it by appending more tags and returns it.

Hope I've made myself clear.

Upvotes: 0

Views: 337

Answers (1)

Thilo
Thilo

Reputation: 262824

If the parser cannot parse the XML (and aborts with an exception), where are you going to get your XML object from?

If you think that in your flow of operation no XML exception can ever really happen (which the compiler of course cannot guarantee), then assume just that, catch the exception, log a "oops, that should never have happened", re-throw a RuntimeException and don't worry about it any longer (it won't ever happen, right?)

String fault = "<Fault><FaultCode>" + e.getClass().getName() + 
  "</FaultCode> <FaultDescription>" + e.getMessage() 
   + "</FaultDescription></Fault>";
return XmlObject.Factory.parse(fault);

I think (if that error message does not need escaping), you can be sure that this will never fail. So that would fit the above pattern.

I don't know if that is "checked-exception-free", but you could forgo the XML string and re-parsing it and construct a DOM programmatically instead.

  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  Document doc = dbf.newDocumentBuilder().newDocument();
  Element rootElement = doc.createElement("fault");
  // etc ...

I don't know if that is "checked-exception-free",

Looking at the Javadocs: Nope. All kinds of configuration exceptions. :-(

Upvotes: 1

Related Questions