Skip to content

Exceptions thrown by custom error handlers are not recorded in RestTemplate observations #32060

@Vsevolod123

Description

@Vsevolod123

RestTemplate set error to observation only for IOException and RestClientException and there is no way to customize that.

I tried error handler like this

@RequiredArgsConstructor
public class DefaultResponseRestTemplateErrorHandler extends DefaultResponseErrorHandler {
    private final ObservationRegistry observationRegistry;

    @Override
    public void handleError(@NonNull ClientHttpResponse clientHttpResponse) throws IOException {
        final var status = (HttpStatus) clientHttpResponse.getStatusCode();
        final var exception = switch (status) {
            case BAD_REQUEST -> new RuntimeException("bad request");
            case UNAUTHORIZED -> new RuntimeException("unauthorized");
            case FORBIDDEN -> new RuntimeException("forbidden");
            case GONE -> new RuntimeException("gone");
            default -> new RuntimeException("other");
        };
        
        Optional.ofNullable(observationRegistry.getCurrentObservation())
                                .map(Observation::getContext)
                                .filter(ClientRequestObservationContext.class::isInstance)
                                .map(ClientRequestObservationContext.class::cast)
                                .ifPresent(context -> context.setError(exception));
                                
        throw exception;
    }
}

But observationRegistry#getCurrentObservation returns parent Observation (in my case http.server.requests).
We use spring-web 6.0.14.

I think there should be some way for customization.

Metadata

Metadata

Assignees

Labels

in: webIssues in web modules (web, webmvc, webflux, websocket)status: backportedAn issue that has been backported to maintenance branchestype: bugA general bug

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions