Skip to content

feat: set requestId if not provided, log requestId on low level excep… #118

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import com.smartling.api.v2.client.exception.DefaultRestApiExceptionMapper;
import com.smartling.api.v2.client.exception.RestApiExceptionHandler;
import com.smartling.api.v2.client.exception.RestApiExceptionMapper;
import com.smartling.api.v2.client.request.RequestContextFilter;
import com.smartling.api.v2.client.request.RequestContextInvocationHandler;
import com.smartling.api.v2.client.unmarshal.DetailsDeserializer;
import com.smartling.api.v2.client.unmarshal.RestApiContextResolver;
import com.smartling.api.v2.client.unmarshal.RestApiResponseReaderInterceptor;
Expand Down Expand Up @@ -40,6 +42,7 @@
import javax.ws.rs.client.ClientResponseFilter;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.ReaderInterceptor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Collections;
import java.util.HashMap;
Expand Down Expand Up @@ -252,11 +255,15 @@ <T> T build(
for (final ClientResponseFilter filter : clientResponseFilters)
client.register(filter);

client.register(new DefaultRequestIdFilter());
client.register(new RequestContextFilter());

final T proxy = client.proxy(klass);
final RestApiExceptionHandler exceptionHandler = new RestApiExceptionHandler(exceptionMapper != null ? exceptionMapper : new DefaultRestApiExceptionMapper());
final ExceptionDecoratorInvocationHandler<T> handler = new ExceptionDecoratorInvocationHandler<>(proxy, exceptionHandler);
final CloseClientInvocationHandler closeClientInvocationHandler = new CloseClientInvocationHandler(handler, client.getResteasyClient());
InvocationHandler handler = new ExceptionDecoratorInvocationHandler<>(proxy, exceptionHandler);
handler = new CloseClientInvocationHandler(handler, client.getResteasyClient());
handler = new RequestContextInvocationHandler(handler);

return (T) Proxy.newProxyInstance(klass.getClassLoader(), new Class[] { klass }, closeClientInvocationHandler);
return (T) Proxy.newProxyInstance(klass.getClassLoader(), new Class[] { klass }, handler);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.smartling.api.v2.client;

import org.apache.commons.lang3.StringUtils;

import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import java.io.IOException;
import java.util.UUID;

public class DefaultRequestIdFilter implements ClientRequestFilter
{
private static final String REQUEST_ID_HEADER = "X-SL-RequestId";

@Override
public void filter(ClientRequestContext requestContext) throws IOException
{
String requestId = requestContext.getHeaderString(REQUEST_ID_HEADER);
if (StringUtils.isBlank(requestId))
{
requestContext.getHeaders().addFirst(REQUEST_ID_HEADER, UUID.randomUUID().toString());
}
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package com.smartling.api.v2.client.exception;

import com.smartling.api.v2.client.request.RequestContextHolder;
import com.smartling.api.v2.response.ErrorResponse;
import lombok.extern.slf4j.Slf4j;

import javax.ws.rs.ProcessingException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.client.ResponseProcessingException;
import javax.ws.rs.core.Response;
import java.lang.reflect.InvocationTargetException;

Expand Down Expand Up @@ -39,9 +41,13 @@ else if (throwable instanceof ProcessingException && throwable.getCause() instan
{
restApiRuntimeException = (RestApiRuntimeException)throwable.getCause();
}
else if (throwable instanceof ResponseProcessingException)
{
restApiRuntimeException = new RestApiRuntimeException(throwable, ((ResponseProcessingException) throwable).getResponse(), null);
}
else
{
restApiRuntimeException = new RestApiRuntimeException(throwable);
restApiRuntimeException = new RestApiRuntimeException(throwable, RequestContextHolder.getContext());
}

restApiRuntimeException.setErrorDetails(errorDetails);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
package com.smartling.api.v2.client.exception;

import com.smartling.api.v2.client.request.RequestContext;
import com.smartling.api.v2.response.Error;
import com.smartling.api.v2.response.ErrorResponse;
import com.smartling.api.v2.response.ResponseCode;
import lombok.extern.slf4j.Slf4j;

import java.util.Collections;
import java.util.List;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import java.util.Collections;
import java.util.List;

@Slf4j
public class RestApiRuntimeException extends WebApplicationException
Expand All @@ -25,6 +26,12 @@ public RestApiRuntimeException(final Throwable cause)
this.errorResponse = null;
}

public RestApiRuntimeException(final Throwable cause, RequestContext requestContext)
{
super(cause, buildErrorResponse(requestContext));
this.errorResponse = null;
}

public RestApiRuntimeException(final Throwable cause, final Response response, final ErrorResponse errorResponse)
{
super(cause, response);
Expand All @@ -37,11 +44,7 @@ public void setErrorDetails(String errorDetails) {

public int getStatus()
{
final Response response = getResponse();
if (response == null)
return 500;

return response.getStatus();
return getResponse().getStatus();
}

public ResponseCode getResponseCode()
Expand All @@ -64,7 +67,7 @@ public List<Error> getErrors()
@Override
public String getMessage()
{
final String requestId = getResponse().getHeaderString(REQUEST_ID_HEADER);
String requestId = getResponse().getHeaderString(REQUEST_ID_HEADER);

final StringBuilder errorMessage = new StringBuilder();

Expand All @@ -89,4 +92,17 @@ public String getMessage()

return errorMessage.toString();
}

private static Response buildErrorResponse(RequestContext requestContext)
{
if (requestContext != null && requestContext.getHeaders() != null)
{
return Response
.status(Response.Status.INTERNAL_SERVER_ERROR)
.header(REQUEST_ID_HEADER, requestContext.getHeaders().getFirst(REQUEST_ID_HEADER))
.build();
}

return Response.serverError().build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.smartling.api.v2.client.request;

import lombok.Data;
import org.jboss.resteasy.specimpl.MultivaluedMapImpl;

import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.core.MultivaluedMap;
import java.net.URI;

@Data
public class RequestContext
{
private final String method;
private final URI uri;
private final MultivaluedMap<String, Object> headers;

public static RequestContext fromClientRequestContext(ClientRequestContext context)
{
MultivaluedMap<String, Object> headers = new MultivaluedMapImpl<>();
headers.putAll(context.getHeaders());

return new RequestContext(context.getMethod(), context.getUri(), headers);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.smartling.api.v2.client.request;

import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import java.io.IOException;

public class RequestContextFilter implements ClientRequestFilter
{
@Override
public void filter(ClientRequestContext clientRequestContext) throws IOException
{
RequestContextHolder.setContext(RequestContext.fromClientRequestContext(clientRequestContext));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.smartling.api.v2.client.request;

public class RequestContextHolder
{
private static final ThreadLocal<RequestContext> REQUEST_CONTEXT = new ThreadLocal<>();

public static void setContext(RequestContext requestContext)
{
REQUEST_CONTEXT.set(requestContext);
}

public static RequestContext getContext()
{
return REQUEST_CONTEXT.get();
}

public static void clearContext()
{
REQUEST_CONTEXT.remove();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.smartling.api.v2.client.request;

import lombok.RequiredArgsConstructor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

@RequiredArgsConstructor
public class RequestContextInvocationHandler implements InvocationHandler
{
private final InvocationHandler delegate;

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
try
{
return delegate.invoke(proxy, method, args);
}
finally
{
RequestContextHolder.clearContext();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package com.smartling.api.v2.client;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.core.MultivaluedMap;

import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class DefaultRequestIdFilterTest
{
private static final String REQUEST_ID_HEADER = "X-SL-RequestId";

@Mock
private ClientRequestContext requestContext;

@Mock
private MultivaluedMap<String, Object> headers;

private final DefaultRequestIdFilter filter = new DefaultRequestIdFilter();

@Before
public void setUp()
{
when(requestContext.getHeaders()).thenReturn(headers);
}

@Test
public void shouldNotAddHeaderWhenRequestIdHeaderExists() throws Exception
{
// Given
when(requestContext.getHeaderString(REQUEST_ID_HEADER)).thenReturn("existing-request-id");

// When
filter.filter(requestContext);

// Then
verifyNoMoreInteractions(headers);
}

@Test
public void shouldAddHeaderWhenRequestIdHeaderDoesNotExist() throws Exception
{
// Given
when(requestContext.getHeaderString(REQUEST_ID_HEADER)).thenReturn(null);

// When
filter.filter(requestContext);

// Then
verify(headers).addFirst(eq(REQUEST_ID_HEADER), any());
verifyNoMoreInteractions(headers);
}

@Test
public void shouldAddHeaderWhenRequestIdHeaderIsEmpty() throws Exception
{
// Given
when(requestContext.getHeaderString(REQUEST_ID_HEADER)).thenReturn("");

// When
filter.filter(requestContext);

// Then
verify(headers).addFirst(eq(REQUEST_ID_HEADER), any());
verifyNoMoreInteractions(headers);
}

@Test
public void shouldAddHeaderWhenRequestIdHeaderIsWhitespace() throws Exception
{
// Given
when(requestContext.getHeaderString(REQUEST_ID_HEADER)).thenReturn(" ");

// When
filter.filter(requestContext);

// Then
verify(headers).addFirst(eq(REQUEST_ID_HEADER), any());
verifyNoMoreInteractions(headers);
}
}
Loading