Add ProblemDetail and @ExceptionHandler support

ProblemDetail is a representation of an RFC 7807 "problem", and this
commits adds support for it in Spring MVC and WebFlux as a return value
from `@ExceptionHandler` methods, optionally wrapped with
ResponseEntity for headers.

See gh-27052
This commit is contained in:
rstoyanchev
2022-02-23 13:00:01 +00:00
parent 65394b00ea
commit 714d451260
6 changed files with 425 additions and 20 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -31,6 +31,7 @@ import java.util.Date;
import java.util.Set;
import jakarta.servlet.FilterChain;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
@@ -46,6 +47,7 @@ import org.springframework.http.HttpMethod;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ProblemDetail;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
@@ -77,6 +79,8 @@ import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.springframework.http.MediaType.APPLICATION_OCTET_STREAM;
import static org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON;
import static org.springframework.http.MediaType.APPLICATION_PROBLEM_JSON_VALUE;
import static org.springframework.http.MediaType.TEXT_PLAIN;
import static org.springframework.web.servlet.HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE;
@@ -103,6 +107,8 @@ public class HttpEntityMethodProcessorMockTests {
private HttpMessageConverter<Object> resourceRegionMessageConverter;
private HttpMessageConverter<Object> jsonMessageConverter;
private MethodParameter paramHttpEntity;
private MethodParameter paramRequestEntity;
@@ -123,6 +129,8 @@ public class HttpEntityMethodProcessorMockTests {
private MethodParameter returnTypeInt;
private MethodParameter returnTypeProblemDetail;
private ModelAndViewContainer mavContainer;
private MockHttpServletRequest servletRequest;
@@ -147,8 +155,12 @@ public class HttpEntityMethodProcessorMockTests {
given(resourceRegionMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.ALL));
given(resourceRegionMessageConverter.getSupportedMediaTypes(any())).willReturn(Collections.singletonList(MediaType.ALL));
jsonMessageConverter = mock(HttpMessageConverter.class);
given(jsonMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.APPLICATION_PROBLEM_JSON));
given(jsonMessageConverter.getSupportedMediaTypes(any())).willReturn(Collections.singletonList(MediaType.APPLICATION_PROBLEM_JSON));
processor = new HttpEntityMethodProcessor(Arrays.asList(
stringHttpMessageConverter, resourceMessageConverter, resourceRegionMessageConverter));
stringHttpMessageConverter, resourceMessageConverter, resourceRegionMessageConverter, jsonMessageConverter));
Method handle1 = getClass().getMethod("handle1", HttpEntity.class, ResponseEntity.class,
Integer.TYPE, RequestEntity.class);
@@ -163,6 +175,7 @@ public class HttpEntityMethodProcessorMockTests {
returnTypeHttpEntitySubclass = new MethodParameter(getClass().getMethod("handle2x", HttpEntity.class), -1);
returnTypeInt = new MethodParameter(getClass().getMethod("handle3"), -1);
returnTypeResponseEntityResource = new MethodParameter(getClass().getMethod("handle5"), -1);
returnTypeProblemDetail = new MethodParameter(getClass().getMethod("handle6"), -1);
mavContainer = new ModelAndViewContainer();
servletRequest = new MockHttpServletRequest("GET", "/foo");
@@ -184,6 +197,7 @@ public class HttpEntityMethodProcessorMockTests {
assertThat(processor.supportsReturnType(returnTypeResponseEntity)).as("ResponseEntity return type not supported").isTrue();
assertThat(processor.supportsReturnType(returnTypeHttpEntity)).as("HttpEntity return type not supported").isTrue();
assertThat(processor.supportsReturnType(returnTypeHttpEntitySubclass)).as("Custom HttpEntity subclass not supported").isTrue();
assertThat(processor.supportsReturnType(returnTypeProblemDetail)).isTrue();
assertThat(processor.supportsReturnType(paramRequestEntity)).as("RequestEntity parameter supported").isFalse();
assertThat(processor.supportsReturnType(returnTypeInt)).as("non-ResponseBody return type supported").isFalse();
}
@@ -268,6 +282,36 @@ public class HttpEntityMethodProcessorMockTests {
verify(stringHttpMessageConverter).write(eq(body), eq(accepted), isA(HttpOutputMessage.class));
}
@Test
public void shouldHandleProblemDetail() throws Exception {
ProblemDetail problemDetail = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
servletRequest.addHeader("Accept", APPLICATION_PROBLEM_JSON_VALUE);
given(jsonMessageConverter.canWrite(ProblemDetail.class, APPLICATION_PROBLEM_JSON)).willReturn(true);
processor.handleReturnValue(problemDetail, returnTypeProblemDetail, mavContainer, webRequest);
assertThat(mavContainer.isRequestHandled()).isTrue();
assertThat(webRequest.getNativeResponse(HttpServletResponse.class).getStatus()).isEqualTo(400);
verify(jsonMessageConverter).write(eq(problemDetail), eq(APPLICATION_PROBLEM_JSON), isA(HttpOutputMessage.class));
assertThat(problemDetail).isNotNull()
.extracting(ProblemDetail::getInstance).isNotNull()
.extracting(URI::toString)
.as("Instance was not set to the request path")
.isEqualTo(servletRequest.getRequestURI());
// But if instance is set, it should be respected
problemDetail.setInstance(URI.create("/something/else"));
processor.handleReturnValue(problemDetail, returnTypeProblemDetail, mavContainer, webRequest);
assertThat(problemDetail).isNotNull()
.extracting(ProblemDetail::getInstance).isNotNull()
.extracting(URI::toString)
.as("Instance was not set to the request path")
.isEqualTo("/something/else");
}
@Test
public void shouldHandleReturnValueWithProducibleMediaType() throws Exception {
String body = "Foo";
@@ -797,6 +841,11 @@ public class HttpEntityMethodProcessorMockTests {
return null;
}
@SuppressWarnings("unused")
public ProblemDetail handle6() {
return null;
}
@SuppressWarnings("unused")
public static class CustomHttpEntity extends HttpEntity<Object> {
}