Не знаю, что случилось, но я в недоумении, где мой ответ увозят.Джерси-клиент получает неправильный ответ
Я использую джерси 2.15 и у меня есть настраиваемый механизм отображения исключений. Я переместил некоторый код, и теперь мой обработчик исключений работает не так, как ожидалось, но проблема заключается в том, что гризли захватывает мой ответ.
В этом суть моей проблемы, если вы видите в моем протоколе регистрации, сервер правильно обрабатывает мое исключение и сообщает мне, что он отправляет ответ с помощью приложения/xml. Но когда я печатаю ответ как String от клиента, это не ожидаемое сообщение об ошибке, а общая ошибка 400 с веб-сервера.
Feb 17, 2015 1:37:20 PM org.glassfish.jersey.filter.LoggingFilter log
INFO: 2 * Server responded with a response on thread Grizzly-worker(2)
2 < 400
2 < Content-Type: application/xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><constraintViolationErrorResponse><responseCode>2</responseCode><violations><path>createCustomer.arg0.customerContact</path><message>customerContact is a required field</message></violations><violations><path>createCustomer.arg0.technicalContact</path><message>technicalContact is a required field</message></violations><violations><path>createCustomer.arg0.spCustomerID1</path><message>spCustomerID1 is a required field</message></violations><violations><path>createCustomer.arg0.customerAddress</path><message>customerAddress is a required field</message></violations><violations><path>createCustomer.arg0.customerName</path><message>customerName is a required field</message></violations></constraintViolationErrorResponse>
Response is <html><head><title>Grizzly 2.3.16</title><style><!--div.header {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#003300;font-size:22px;-moz-border-radius-topleft: 10px;border-top-left-radius: 10px;-moz-border-radius-topright: 10px;border-top-right-radius: 10px;padding-left: 5px}div.body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:#FFFFCC;font-size:16px;padding-top:10px;padding-bottom:10px;padding-left:10px}div.footer {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#666633;font-size:14px;-moz-border-radius-bottomleft: 10px;border-bottom-left-radius: 10px;-moz-border-radius-bottomright: 10px;border-bottom-right-radius: 10px;padding-left: 5px}BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;}B {font-family:Tahoma,Arial,sans-serif;color:black;}A {color : black;}HR {color : #999966;}--></style> </head><body><div class="header">Bad Request</div><div class="body">Bad Request</div><div class="footer">Grizzly 2.3.16</div></body></html>
Media type is text/html; charset=ISO-8859-1
Feb 17, 2015 1:37:20 PM org.glassfish.grizzly.http.server.NetworkListener shutdownNow
INFO: Stopped listener bound to [localhost:9998]
Вот мое исключение картографа, который обрабатывает ConstraintViolationException
@Provider
public class ConstraintViolationExceptionMapper implements ExceptionMapper<ConstraintViolationException> {
//private static final Logger logger = Logger.getLogger(ConstraintViolationExceptionMapper.class.getName());
public Response toResponse(ConstraintViolationException exception) {
final int violationCount = exception.getConstraintViolations().size();
ConstraintViolation<?>[] constraintViolations = exception.getConstraintViolations().toArray(
new ConstraintViolation<?>[violationCount]);
Violation[] violations = new Violation[exception.getConstraintViolations().size()];
for (int i = 0; i < violationCount; i++) {
ConstraintViolation<?> cv = constraintViolations[i];
Violation violation = new Violation(cv.getPropertyPath().toString(), cv.getMessage());
violations[i] = violation;
}
ConstraintViolationErrorResponse responseEntity = new ConstraintViolationErrorResponse();
responseEntity.setViolations(violations);
return Response.status(Response.Status.BAD_REQUEST).entity(responseEntity).build();
}
}
Это тестовый модуль я использую, где он распечатав ответ от клиента для отладки.
@Test
public void testConstraintViolationException() {
logger.info("testConstraintViolationException");
Customer customer = new Customer();
Entity<Customer> customerEntity = Entity.entity(customer, MediaType.APPLICATION_XML);
Response response = target("customer").request().accept(MediaType.APPLICATION_XML).post(customerEntity, Response.class);
if (response.getStatusInfo() != Status.OK) {
final String res = response.readEntity(new GenericType<String>() {});
System.out.println("Response is " + res);
System.out.println("Media type is " + response.getMediaType());
ConstraintViolationErrorResponse responseEntity = response.readEntity(ConstraintViolationErrorResponse.class);
assert (responseEntity.getClass() == ConstraintViolationErrorResponse.class);
ConstraintViolationErrorResponse constraintResponse = (ConstraintViolationErrorResponse) responseEntity;
assert (constraintResponse.getViolations().length > 0);
for (Violation v : constraintResponse.getViolations()) {
logger.fine("Constraint Violation Path -> " + v.getPath() + " Message -> " + v.getMessage());
}
}
}
Быстрое примечание, если я возвращаю ACCEPTED или OK в качестве кода ответа, ответ успешно обработан. –