use of com.linkedin.r2.message.rest.RestException in project rest.li by linkedin.
the class TestRestLiServer method testMessageAndDetailsErrorFormat.
@Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "protocolVersions")
public void testMessageAndDetailsErrorFormat(final ProtocolVersion protocolVersion, final String errorResponseHeaderName, final RestOrStream restOrStream) throws Exception {
final StatusCollectionResource statusResource = getMockResource(StatusCollectionResource.class);
final DataMap details = new DataMap();
details.put("errorKey", "errorDetail");
EasyMock.expect(statusResource.get(eq(1L))).andThrow(new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Mock Exception").setErrorDetails(details)).once();
EasyMock.replay(statusResource);
Callback<RestResponse> restResponseCallback = new Callback<RestResponse>() {
@Override
public void onSuccess(RestResponse restResponse) {
fail();
}
@Override
public void onError(Throwable e) {
assertTrue(e instanceof RestException);
RestException restException = (RestException) e;
RestResponse restResponse = restException.getResponse();
try {
assertEquals(restResponse.getStatus(), 500);
assertTrue(restResponse.getEntity().length() > 0);
assertEquals(restResponse.getHeader(errorResponseHeaderName), RestConstants.HEADER_VALUE_ERROR);
ErrorResponse responseBody = DataMapUtils.read(restResponse.getEntity().asInputStream(), ErrorResponse.class);
// in this test, we're using the _serverWithCustomErrorResponseConfig (see below), which has been configure to use the
// MESSAGE_AND_DETAILS ErrorResponseFormat, so stack trace and other error response parts should be absent
assertEquals(responseBody.getMessage(), "Mock Exception");
assertEquals(responseBody.getErrorDetails().data().getString("errorKey"), "errorDetail");
assertFalse(responseBody.hasExceptionClass());
assertFalse(responseBody.hasStackTrace());
assertFalse(responseBody.hasStatus());
EasyMock.verify(statusResource);
EasyMock.reset(statusResource);
} catch (Exception e2) {
fail(e2.toString());
}
}
};
if (restOrStream == RestOrStream.REST) {
RestRequest request = new RestRequestBuilder(new URI("/statuses/1")).setHeader(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, protocolVersion.toString()).build();
_serverWithCustomErrorResponseConfig.handleRequest(request, new RequestContext(), restResponseCallback);
} else {
StreamRequest streamRequest = new StreamRequestBuilder(new URI("/statuses/1")).setHeader(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, protocolVersion.toString()).build(EntityStreams.emptyStream());
Callback<StreamResponse> callback = new Callback<StreamResponse>() {
@Override
public void onSuccess(StreamResponse streamResponse) {
fail();
}
@Override
public void onError(Throwable e) {
Messages.toRestException((StreamException) e, new Callback<RestException>() {
@Override
public void onError(Throwable e) {
Assert.fail();
}
@Override
public void onSuccess(RestException result) {
restResponseCallback.onError(result);
}
});
}
};
_serverWithCustomErrorResponseConfig.handleRequest(streamRequest, new RequestContext(), callback);
}
}
use of com.linkedin.r2.message.rest.RestException in project rest.li by linkedin.
the class TestRestLiServer method testRestRequestResponseAttachmentsDesired.
@Test
public void testRestRequestResponseAttachmentsDesired() throws Exception {
//This test verifies that a RestRequest sent to the RestLiServer throws an exception if the accept type
//includes multipart related
RestRequest acceptTypeMultiPartRelated = new RestRequestBuilder(new URI("/statuses/abcd")).setHeader(RestConstants.HEADER_ACCEPT, RestConstants.HEADER_VALUE_MULTIPART_RELATED).build();
Callback<RestResponse> callback = new Callback<RestResponse>() {
@Override
public void onSuccess(RestResponse restResponse) {
fail();
}
@Override
public void onError(Throwable e) {
assertTrue(e instanceof RestException);
RestException restException = (RestException) e;
RestResponse restResponse = restException.getResponse();
assertEquals(restResponse.getStatus(), 406);
assertTrue(restResponse.getEntity().length() > 0);
assertEquals(restResponse.getEntity().asString(Charset.defaultCharset()), "This server cannot handle requests with an accept type of multipart/related");
}
};
_server.handleRequest(acceptTypeMultiPartRelated, new RequestContext(), callback);
}
use of com.linkedin.r2.message.rest.RestException in project rest.li by linkedin.
the class TestRestLiServer method testBadRequest.
private void testBadRequest(RestLiServer restLiServer, final ProtocolVersion clientProtocolVersion, String headerConstant, final RestOrStream restOrStream) throws URISyntaxException {
Callback<RestResponse> restResponseCallback = new Callback<RestResponse>() {
@Override
public void onSuccess(RestResponse restResponse) {
fail("The request should have failed!");
}
@Override
public void onError(Throwable e) {
assertEquals(((RestException) e).getResponse().getStatus(), 400);
String expectedErrorMessage = "Rest.li protocol version " + clientProtocolVersion + " used by the client is not supported!";
assertEquals(e.getCause().getMessage(), expectedErrorMessage);
}
};
if (restOrStream == RestOrStream.REST) {
RestRequest request = new RestRequestBuilder(new URI("/statuses/1")).setHeader(headerConstant, clientProtocolVersion.toString()).build();
restLiServer.handleRequest(request, new RequestContext(), restResponseCallback);
} else {
StreamRequest streamRequest = new StreamRequestBuilder(new URI("/statuses/1")).setHeader(headerConstant, clientProtocolVersion.toString()).build(EntityStreams.emptyStream());
Callback<StreamResponse> callback = new Callback<StreamResponse>() {
@Override
public void onSuccess(StreamResponse streamResponse) {
fail("The request should have failed!");
}
@Override
public void onError(Throwable e) {
Messages.toRestException((StreamException) e, new Callback<RestException>() {
@Override
public void onError(Throwable e) {
Assert.fail();
}
@Override
public void onSuccess(RestException result) {
restResponseCallback.onError(result);
}
});
}
};
restLiServer.handleRequest(streamRequest, new RequestContext(), callback);
}
}
use of com.linkedin.r2.message.rest.RestException in project rest.li by linkedin.
the class TestRestLiCallback method testOnErrorWithFiltersNotHandlingAppEx.
@SuppressWarnings("unchecked")
@Test
public void testOnErrorWithFiltersNotHandlingAppEx() throws Exception {
Exception exFromApp = new RuntimeException("Runtime exception from app");
RestLiServiceException appException = new RestLiServiceException(HttpStatus.S_404_NOT_FOUND);
RequestExecutionReport executionReport = new RequestExecutionReportBuilder().build();
RestLiResponseAttachments responseAttachments = new RestLiResponseAttachments.Builder().build();
final Map<String, String> headersFromApp = Maps.newHashMap();
headersFromApp.put("Key", "Input");
final Map<String, String> headersFromFilter = Maps.newHashMap();
headersFromFilter.put("Key", "Output");
RestLiResponseDataImpl responseData = new RestLiResponseDataImpl(appException, headersFromApp, Collections.<HttpCookie>emptyList());
responseData.setResponseEnvelope(new CreateResponseEnvelope(new EmptyRecord(), responseData));
PartialRestResponse partialResponse = new PartialRestResponse.Builder().build();
when(_requestExecutionReportBuilder.build()).thenReturn(executionReport);
when(_responseHandler.buildExceptionResponseData(eq(_restRequest), eq(_routingResult), any(RestLiServiceException.class), anyMap(), anyList())).thenReturn(responseData);
when(_responseHandler.buildPartialResponse(_routingResult, responseData)).thenReturn(partialResponse);
// Mock the behavior of the first filter.
doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
Throwable t = (Throwable) args[0];
FilterRequestContext requestContext = (FilterRequestContext) args[1];
FilterResponseContext responseContext = (FilterResponseContext) args[2];
// Verify incoming data.
assertEquals(HttpStatus.S_404_NOT_FOUND, responseContext.getResponseData().getStatus());
assertEquals(headersFromApp, responseContext.getResponseData().getHeaders());
assertNull(responseContext.getResponseData().getRecordResponseEnvelope().getRecord());
// Modify data in filter.
setStatus(responseContext, HttpStatus.S_400_BAD_REQUEST);
responseContext.getResponseData().getHeaders().clear();
return completedFutureWithError(responseContext.getResponseData().getServiceException());
}
}).doAnswer(new Answer<Object>() {
// Mock the behavior of the second filter.
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
Throwable t = (Throwable) args[0];
FilterRequestContext requestContext = (FilterRequestContext) args[1];
FilterResponseContext responseContext = (FilterResponseContext) args[2];
// Verify incoming data.
assertEquals(HttpStatus.S_400_BAD_REQUEST, responseContext.getResponseData().getStatus());
//assertTrue(responseContext.getResponseData().getHeaders().isEmpty());
assertNull(responseContext.getResponseData().getRecordResponseEnvelope().getRecord());
// Modify data in filter.
setStatus(responseContext, HttpStatus.S_403_FORBIDDEN);
responseContext.getResponseData().getHeaders().putAll(headersFromFilter);
return completedFutureWithError(responseContext.getResponseData().getServiceException());
}
}).when(_filter).onError(any(Throwable.class), eq(_filterRequestContext), any(FilterResponseContext.class));
RestException restException = new RestException(new RestResponseBuilder().build());
when(_responseHandler.buildRestException(any(RestLiServiceException.class), eq(partialResponse))).thenReturn(restException);
// invoke request filters so cursor is in correct place
when(_filter.onRequest(any(FilterRequestContext.class))).thenReturn(CompletableFuture.completedFuture(null));
_twoFilterChain.onRequest(_filterRequestContext, _filterResponseContextFactory);
// Invoke.
_twoFilterRestLiCallback.onError(exFromApp, executionReport, _requestAttachmentReader, responseAttachments);
// Verify.
assertNotNull(responseData);
assertEquals(HttpStatus.S_403_FORBIDDEN, responseData.getStatus());
assertNull(responseData.getRecordResponseEnvelope().getRecord());
assertTrue(responseData.isErrorResponse());
assertEquals(responseData.getServiceException().getErrorDetails(), appException.getErrorDetails());
assertEquals(responseData.getServiceException().getOverridingFormat(), appException.getOverridingFormat());
assertEquals(responseData.getServiceException().getServiceErrorCode(), appException.getServiceErrorCode());
assertEquals(responseData.getServiceException().getMessage(), appException.getMessage());
Map<String, String> expectedHeaders = buildErrorHeaders();
expectedHeaders.put("Key", "Output");
assertEquals(expectedHeaders, responseData.getHeaders());
ArgumentCaptor<RestLiServiceException> exCapture = ArgumentCaptor.forClass(RestLiServiceException.class);
verify(_responseHandler, times(1)).buildExceptionResponseData(eq(_restRequest), eq(_routingResult), exCapture.capture(), anyMap(), anyList());
verify(_responseHandler).buildPartialResponse(_routingResult, responseData);
verify(_responseHandler).buildRestException(exCapture.capture(), eq(partialResponse));
verify(_callback).onError(restException, executionReport, _requestAttachmentReader, responseAttachments);
verify(_restRequest, times(1)).getHeaders();
verifyZeroInteractions(_routingResult);
verifyNoMoreInteractions(_restRequest, _responseHandler, _callback);
final RestLiServiceException restliEx1 = exCapture.getAllValues().get(0);
assertNotNull(restliEx1);
assertEquals(HttpStatus.S_500_INTERNAL_SERVER_ERROR, restliEx1.getStatus());
assertEquals(exFromApp.getMessage(), restliEx1.getMessage());
assertEquals(exFromApp, restliEx1.getCause());
final RestLiServiceException restliEx2 = exCapture.getAllValues().get(1);
assertNotNull(restliEx2);
assertEquals(HttpStatus.S_403_FORBIDDEN, restliEx2.getStatus());
}
use of com.linkedin.r2.message.rest.RestException in project rest.li by linkedin.
the class TestRestLiCallback method testOnErrorWithFiltersExceptionFromSecondFilter.
@SuppressWarnings("unchecked")
@Test
public void testOnErrorWithFiltersExceptionFromSecondFilter() throws Exception {
// App stuff.
RestLiServiceException exFromApp = new RestLiServiceException(HttpStatus.S_404_NOT_FOUND, "App failure");
RequestExecutionReport executionReport = new RequestExecutionReportBuilder().build();
RestLiResponseAttachments responseAttachments = new RestLiResponseAttachments.Builder().build();
RestLiResponseDataImpl responseAppData = new RestLiResponseDataImpl(exFromApp, Collections.<String, String>emptyMap(), Collections.<HttpCookie>emptyList());
responseAppData.setResponseEnvelope(new CreateResponseEnvelope(null, responseAppData));
// Filter stuff.
final Exception exFromSecondFilter = new RuntimeException("Runtime exception from second filter");
RestLiServiceException exception = new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, exFromSecondFilter);
RestLiResponseDataImpl responseFilterData = new RestLiResponseDataImpl(exception, Collections.<String, String>emptyMap(), Collections.<HttpCookie>emptyList());
responseFilterData.setResponseEnvelope(new CreateResponseEnvelope(null, responseFilterData));
PartialRestResponse partialResponse = new PartialRestResponse.Builder().build();
RestException restException = new RestException(new RestResponseBuilder().build());
// Setup.
when(_requestExecutionReportBuilder.build()).thenReturn(executionReport);
when(_responseHandler.buildExceptionResponseData(eq(_restRequest), eq(_routingResult), any(RestLiServiceException.class), anyMap(), anyList())).thenReturn(responseAppData).thenReturn(responseFilterData);
when(_responseHandler.buildPartialResponse(_routingResult, responseAppData)).thenReturn(partialResponse);
when(_restRequest.getHeaders()).thenReturn(null);
when(_responseHandler.buildRestException(any(RestLiServiceException.class), eq(partialResponse))).thenReturn(restException);
// Mock filter behavior.
doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
Throwable t = (Throwable) args[0];
FilterRequestContext requestContext = (FilterRequestContext) args[1];
FilterResponseContext responseContext = (FilterResponseContext) args[2];
assertEquals(responseContext.getResponseData().getStatus(), HttpStatus.S_404_NOT_FOUND);
assertNull(responseContext.getResponseData().getRecordResponseEnvelope().getRecord());
assertTrue(responseContext.getResponseData().getHeaders().isEmpty());
// Modify data.
setStatus(responseContext, HttpStatus.S_402_PAYMENT_REQUIRED);
return completedFutureWithError(t);
}
}).doThrow(exFromSecondFilter).when(_filter).onError(any(Throwable.class), eq(_filterRequestContext), any(FilterResponseContext.class));
// invoke request filters so cursor is in correct place
when(_filter.onRequest(any(FilterRequestContext.class))).thenReturn(CompletableFuture.completedFuture(null));
_twoFilterChain.onRequest(_filterRequestContext, _filterResponseContextFactory);
// Invoke.
_twoFilterRestLiCallback.onError(exFromApp, executionReport, _requestAttachmentReader, responseAttachments);
// Verify.
ArgumentCaptor<RestLiServiceException> wrappedExCapture = ArgumentCaptor.forClass(RestLiServiceException.class);
verify(_responseHandler).buildExceptionResponseData(eq(_restRequest), eq(_routingResult), wrappedExCapture.capture(), anyMap(), anyList());
verify(_responseHandler).buildPartialResponse(_routingResult, responseAppData);
verify(_responseHandler).buildRestException(wrappedExCapture.capture(), eq(partialResponse));
verify(_callback).onError(restException, executionReport, _requestAttachmentReader, responseAttachments);
verify(_restRequest).getHeaders();
verifyZeroInteractions(_routingResult);
verifyNoMoreInteractions(_restRequest, _responseHandler, _callback);
assertNotNull(responseAppData);
assertEquals(HttpStatus.S_500_INTERNAL_SERVER_ERROR, responseAppData.getStatus());
assertNull(responseAppData.getRecordResponseEnvelope().getRecord());
final RestLiServiceException restliEx1 = wrappedExCapture.getAllValues().get(0);
assertEquals(exFromApp, restliEx1);
final RestLiServiceException restliEx2 = wrappedExCapture.getAllValues().get(1);
assertNotNull(restliEx2);
assertEquals(HttpStatus.S_500_INTERNAL_SERVER_ERROR, restliEx2.getStatus());
assertEquals(exFromSecondFilter.getMessage(), restliEx2.getMessage());
assertEquals(exFromSecondFilter, restliEx2.getCause());
}
Aggregations