java - Ensure that web service handles exceptions and always returns a valid response -
i developing web service, no matter what, response should valid, , mean valid in valid format.
that means if web service expected return xml matching particular xsd schema, should return valid xml document, no matter what.
the approach have far (at controller level)
string xmlresponse = this.loaddefaultxml(); try { xmlresponse = this.mycoolservice.mycoolmethod(); } catch (throwable t) { xmlresponse = this.loaddefaultxml(string errormessage) } { return xmlresponse }
where of course lpoaddefaultxml()
load xml document like:
<?xml> <result>ouch, there problem</result>
and loaddefaultxml(string errormessage)
do
<?xml> <result>whatever errormessage contains</result>
of course service level takes cares of normal exceptions, still, feel catching throwable
, using try-catch-finally
way ensure no matter what, in control can return xml.
any better ideas or suggestions?
update:
i using spring mvc 3.2 , jaxb marshalling/unmarshalling of xml. use soap, not using wsdl this.
in spring mvc, when exception thrown during handling of request, dispatcherservlet
consult configured org.springframework.web.servlet.handlerexceptionresolver
s handle thrown exception. resolver can translate exception view show user.
to use it, in short, can either:
- implement
handlerexceptionresolver
interface, matter of implementingresolveexception(exception, handler)
method , returningmodelandview
.
or, prefer:
you use
@exceptionhandler
method annotation within controller specify method invoked when exception of specific type thrown during execution of controller methods. example:@controller public class personcontroller { @requestmapping("person/{id}") @responsebody public person getbyid(@pathvariable string id) { if ("007".equals(id)) { throw new runtimeexception("007 secret agent."); } return personservice.getbyid(id); } @exceptionhandler(runtimeexception.class) // can array @responsebody public string handleruntimeexception(runtimeexception ex, httpservletrequest request) { return "oops! bad happened: "+ex.getmessage(); } }
find more info @ web mvc framework - handling exceptions.
Comments
Post a Comment