2013-02-13 14 views
13

Sto chiamando un servizio REST che restituisce XML e utilizzando Jaxb2Marshaller per eseguire il marshalling delle mie classi (ad esempio Foo, Bar, ecc.). Quindi il mio codice cliente si presenta in questo modo:Come configurare RestTemplate di Spring per restituire null quando viene restituito lo stato HTTP di 404

HashMap<String, String> vars = new HashMap<String, String>(); 
    vars.put("id", "123"); 

    String url = "http://example.com/foo/{id}"; 

    Foo foo = restTemplate.getForObject(url, Foo.class, vars); 

Quando il look-up sul lato server non riesce restituisce un 404 insieme ad alcuni XML. Alla fine ottengo un UnmarshalException generato perché non può leggere l'XML.

Caused by: javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"exception"). Expected elements are <{}foo>,<{}bar> 

Il corpo della risposta è:

<exception> 
    <message>Could not find a Foo for ID 123</message> 
</exception> 

Come posso configurare le RestTemplate in modo che i rendimenti RestTemplate.getForObject()null se un 404 accade?

+0

'getForObject', per impostazione predefinita, deve generare un' HttpClientErrorException' con un 404. Come è stato configurato il 'RestTemplate'? –

+0

@SotiriosDelimanolis Non ho più accesso al codice, ma il comportamento predefinito che descrivi è simile a quello che mi aspettavo in quel momento. (Dovrei prendere l'abitudine di dichiarare le versioni in future domande.) – vegemite4me

risposta

14
Foo foo = null; 
try { 
    foo = restTemplate.getForObject(url, Foo.class, vars); 
} catch (HttpClientErrorException ex) { 
    if (ex.getStatusCode() != HttpStatus.NOT_FOUND) { 
     throw ex; 
    } 
} 
+1

Better do 'if (ex.getStatusCode()! = HttpStatus.NOT_FOUND) { throw ex; } ' – vdimitrov

+0

Modificato, grazie – Tim

Problemi correlati