Reputation: 13813
I am developing a web service, no matter what, the response should always be valid, and I mean valid as in a valid format.
That means that if the web service is expected to return an XML matching a particular XSD schema, it should ALWAYS return a valid XML document, no matter what.
The only approach that I have so far is to do something like this (at controller level)
String xmlResponse = this.loadDefaultXML();
try {
xmlResponse = this.myCoolService.myCoolMethod();
} catch (Throwable t) {
xmlResponse = this.loadDefaultXML(String errorMessage)
} finally {
return xmlResponse
}
Where of course lpoadDefaultXML()
will load an xml document like:
<?xml>
<result>Ouch, there was a problem</result>
And loadDefaultXML(String errorMessage)
will do
<?xml>
<result>WHATEVER errorMessage contains</result>
Of course the service level takes cares of the normal exceptions, still, I feel that catching Throwable
and using the try-catch-finally
is the only way to ensure that no matter what, I will be in control so I can return always an XML.
Any better ideas or suggestions?
UPDATE:
I am using Spring MVC 3.2 and JAXB for the marshalling/unmarshalling of xml. This does use SOAP, also I am not using wsdl for this.
Upvotes: 1
Views: 420
Reputation: 135762
In Spring MVC, when an exception is thrown during the handling of the request, the DispatcherServlet
will consult the configured org.springframework.web.servlet.HandlerExceptionResolver
s to handle the thrown exception. The resolver can then translate the exception to a view to show the user.
To use it, in short, you can either:
HandlerExceptionResolver
interface, which is only a matter of implementing the resolveException(Exception, Handler)
method and returning a ModelAndView
.Or, what I prefer:
You use the @ExceptionHandler
method annotation within a controller to specify which method is invoked when an exception of a specific type is thrown during the execution of controller methods. For example:
@Controller
public class PersonController {
@RequestMapping("person/{id}")
@ResponseBody
public Person getById(@PathVariable String id) {
if ("007".equals(id)) {
throw new RuntimeException("007 is a secret agent.");
}
return personService.getById(id);
}
@ExceptionHandler(RuntimeException.class) // this can be an array
@ResponseBody
public String handleRuntimeException(RuntimeException ex,
HttpServletRequest request) {
return "Oops! Something bad happened: "+ex.getMessage();
}
}
Find more info at Web MVC framework - Handling Exceptions.
Upvotes: 2