2015-01-30 17 views
16

Vorrei rilevare l'eccezione JSON nel mio servizio di assistenza nel caso in cui JSON di input non sia valido.Jersey/Jackson: come catturare l'eccezione JSON?

Getta org.codehaus.jackson.map.JsonMappingException, ma non so come o dove rilevare questa eccezione. Voglio rilevare questa eccezione e inviare una risposta all'errore appropriata.

@JsonInclude(JsonInclude.Include.NON_NULL) 
@Generated("org.jsonschema2pojo") 
@JsonPropertyOrder({ 
     "name", 
     "id" 
}) 
public class Customer { 
    @JsonProperty("name") 
    private String name; 

    @JsonProperty("id") 
    private String id; 
    <setter/getter code> 
} 

public class MyService { 
    @POST 
    @Consumes(MediaType.APPLICATION_JSON) 
    public final Response createCustomer(@Context HttpHeaders headers, 
      Customer customer) { 
     System.out.println("Customer data: " + customer.toString()); 
     return Response.ok("customer created").build(); 
    } 
} 

Tutto funziona bene, ma se il corpo JSON non è ben formata allora getta JsonMappingException eccezione. Voglio cogliere questa eccezione.

+0

Vedi anche: https://java.net/jira/browse/JERSEY-2722 –

risposta

17

Ciò che alla fine ha funzionato per me è stato quello di dichiarare un fornitore ExceptionMapper per JsonMappingException, come ad esempio

import org.codehaus.jackson.map.JsonMappingException; 
import org.springframework.stereotype.Component; 

import javax.ws.rs.core.Response; 
import javax.ws.rs.ext.ExceptionMapper; 
import javax.ws.rs.ext.Provider; 

@Component 
@Provider 
public class JsonMappingExceptionMapper implements ExceptionMapper<JsonMappingException> { 
    @Override 
    public Response toResponse(JsonMappingException exception) { 
     return Response.status(Response.Status.BAD_REQUEST).build(); 
    } 
} 
+0

Questo approccio sembra buono, ma dove posso lanciare e catturare questa eccezione in modo da poter inviare una risposta appropriata in JsonMappingExceptionMapper. toResponse(). Ho implementato JsonMappingExceptionMapper come nel tuo esempio ma non chiamerà il metodo Risposta, Getta JsonMappingException ma non riesco a prenderlo. Qualche idea su dove e come posso prendere JsonMappingException ?? – Neel

+0

Sì, dovrebbe essere lanciato da Jersey se il corpo POST non deserializza nell'oggetto 'Cliente'. Assicurati di aver registrato 'JsonMappingExceptionMapper' con l'applicazione Jersey ... nel mio caso li sto registrando tramite l'integrazione del componente Spring. –

Problemi correlati