2013-06-13 17 views
9

È necessario restituire un codice di errore personalizzato e un messaggio di errore quando si verifica un'eccezione durante il richiamo REST. Abbiamo creato un provider di mapping di eccezioni, funziona bene per le eccezioni dal codice dell'applicazione. Tuttavia, non funziona quando si verifica un'eccezione dal codice CXF (ad esempio, modulo CustomValidationInterceptor che ho scritto).CXF/JAX-RS: Invio Risposta personalizzata dall'intercettore

Ad esempio, se si richiede un parametro percorso non valido (ad esempio numero telefonico non valido). In questo caso, dobbiamo restituire un codice di errore personalizzato e un messaggio di errore in formato JSON, ma non funziona anche se abbiamo creato un provider di mapping di eccezioni per gestire WebApplicationException.

C'è un modo per gestire le eccezioni dagli intercettori cxf e restituire la risposta all'utente con qualcosa di simile al seguente?

{ 
"errorDetail": { 
"errorCode": "404", 
"errorMessage": "Bad Request" 
} 
} 

frammento di codice del mio CustomValidationInterceptor:

public class CustomValidationInterceptor extends AbstractPhaseInterceptor<Message>{ 

    public CustomValidationInterceptor() { 
     super(Phase.PRE_INVOKE); // Put this interceptor in this phase 
    } 

    public void handleMessage(Message message) { 

     MetadataMap<String, String> metadataMap = (MetadataMap<String, String>) message.get("jaxrs.template.parameters"); 

     if(null != metadataMap) { 
      List<String> list = metadataMap.get("phoneNumber"); 
      if(null != list) { 
       String phoneNumber = list.get(0); 
       boolean result = validatePhoneNumber(phoneNumber); 
       if(!result){ 
        throw new TelusServiceException(Response.status(Response.Status.BAD_REQUEST).build(), 400, "phone number not valid"); 
       } 
      } else { 
       throw new TelusServiceException(Response.status(Response.Status.BAD_REQUEST).build(), 400, "phone number not valid"); 
      } 
     } else { 
      throw new TelusServiceException(Response.status(Response.Status.BAD_REQUEST).build(), 400, "phone number not valid"); 
     } 
    } 

    public boolean validatePhoneNumber(String phoneNumber) { 

      Pattern pattern = Pattern.compile("^[1-9]\\d{9}$"); 
      Matcher matcher = pattern.matcher(phoneNumber); 

      if (!matcher.matches()) { 
       return false; 
      } 
      return true; 
    } 

} 

frammento di codice della mia ordinazione Eccezione Mapper Provider

public class TelusExceptionHandler implements ExceptionMapper<TelusServiceException> { 

    public Response toResponse(TelusServiceException exception) { 
     return Response.status(exception.getErrorDetail().getErrorCode()).entity(exception.getErrorDetail()).build(); 
    } 

} 

frammento di codice di TelusServiceException

public class TelusServiceException extends WebApplicationException{ 

// constructors and other methods 

    private ErrorDetail errorDetail = null; 

     public ErrorDetail getErrorDetail() { 
     return errorDetail; 
    } 

    public void setErrorDetail(ErrorDetail errorDetail) { 
     this.errorDetail = errorDetail; 
    } 

     public TelusServiceException(Response response, int errorCode, String errorMessage) { 
     super(response); 

     errorDetail = new ErrorDetail(); 
     errorDetail.setErrorCode(errorCode); 
     errorDetail.setErrorMessage(errorMessage); 
    } 

} 

Snippet di codice di classe ErrorDetail

@XmlRootElement(name="errorDetail") 
public class ErrorDetail { 

    private int errorCode; 
    private String errorMessage; 

    @XmlElement(name = "errorCode") 
    public int getErrorCode() { 
     return errorCode; 
    } 

    public void setErrorCode(int errorCode) { 
     this.errorCode = errorCode; 
    } 
    @XmlElement(name = "errorMessage") 
    public String getErrorMessage() { 
     return errorMessage; 
    } 

    public void setErrorMessage(String errorMessage) { 
     this.errorMessage = errorMessage; 
    } 

} 
+0

Ho corretto il JSON. Si veda – Bhuvan

+0

Qual è il codice di 'TelusServiceException'.' .getErrorDetail() '? – fge

+0

aggiunto snippet di codice di TelusServiceException e ErrorDetail Object – Bhuvan

risposta

7

ho trovato il modo di inviare una risposta personalizzata dalla intercettore, ma ancora non riesco a capire un modo per chiamare la mia CustomExceptionHandler dal intercettore

Codice:

public void handleMessage(Message message) { 

     MetadataMap<String, String> metadataMap = (MetadataMap<String, String>) message.get("jaxrs.template.parameters"); 

     if(null != metadataMap) { 
      List<String> list = metadataMap.get("phoneNumber"); 
      if(null != list) { 
       String phoneNumber = list.get(0); 
       boolean result = validatePhoneNumber(phoneNumber); 
       if(!result){ 
// Create a response object and set it in the message. 
// calling getExchange() will not call your service 
        Response response = Response 
       .status(Response.Status.BAD_REQUEST) 
       .entity(new ErrorDetail(Response.Status.BAD_REQUEST.getStatusCode(), Response.Status.BAD_REQUEST.toString())) 
       .build(); 
     message.getExchange().put(Response.class, response); 
// That's it 
       } 
      } else { 
       Response response = Response 
       .status(Response.Status.BAD_REQUEST) 
       .entity(new ErrorDetail(Response.Status.BAD_REQUEST.getStatusCode(), Response.Status.BAD_REQUEST.toString())) 
       .build(); 
     message.getExchange().put(Response.class, response); 
      } 
     } else { 
      Response response = Response 
       .status(Response.Status.BAD_REQUEST) 
       .entity(new ErrorDetail(Response.Status.BAD_REQUEST.getStatusCode(), Response.Status.BAD_REQUEST.toString())) 
       .build(); 
     message.getExchange().put(Response.class, response); 
     } 
    } 
2

ho sollevato una domanda simile sul gruppo di utenti CXF, vedi:

http://cxf.547215.n5.nabble.com/Handling-exceptions-in-a-JAX-RS-fault-interceptor-when-using-Local-Transport-td5733958.html

Ho finito per sostituire i miei intercettori con ContainerRequestFilter e ContainerResponseFilter e poi il Exception Mapper gestiva felicemente sia le eccezioni delle applicazioni che le eccezioni generate dal filtro.

Spero che questo aiuti.

+0

Forse hai avuto un problema simile: http://stackoverflow.com/questions/37984617/avoid-exception-mapper-through-cxf-interceptor –

Problemi correlati