Add ErrorResponse and ErrorResponseException

ErrorResponse represents a complete error response with status, headers,
and an  RFC 7807 ProblemDetail body.

ErrorResponseException implements ErrorResponse and is usable on its
own or as a base class. ResponseStatusException extends
ErrorResponseException and now also supports RFC 7807 and so does its
sub-hierarchy.

ErrorResponse can be returned from `@ExceptionHandler` methods and is
mapped to ResponseEntity.

See gh-27052
This commit is contained in:
rstoyanchev
2022-02-23 14:52:17 +00:00
parent 714d451260
commit 3efedef161
13 changed files with 415 additions and 90 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 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.
@@ -116,7 +116,7 @@ public class ResponseStatusExceptionResolver extends AbstractHandlerExceptionRes
/**
* Template method that handles an {@link ResponseStatusException}.
* <p>The default implementation applies the headers from
* {@link ResponseStatusException#getResponseHeaders()} and delegates to
* {@link ResponseStatusException#getHeaders()} and delegates to
* {@link #applyStatusAndReason} with the status code and reason from the
* exception.
* @param ex the exception
@@ -130,9 +130,7 @@ public class ResponseStatusExceptionResolver extends AbstractHandlerExceptionRes
protected ModelAndView resolveResponseStatusException(ResponseStatusException ex,
HttpServletRequest request, HttpServletResponse response, @Nullable Object handler) throws Exception {
ex.getResponseHeaders().forEach((name, values) ->
values.forEach(value -> response.addHeader(name, value)));
ex.getHeaders().forEach((name, values) -> values.forEach(value -> response.addHeader(name, value)));
return applyStatusAndReason(ex.getRawStatusCode(), ex.getReason(), response);
}

View File

@@ -44,6 +44,7 @@ import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.ErrorResponse;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.bind.support.WebDataBinderFactory;
@@ -56,7 +57,7 @@ import org.springframework.web.servlet.support.RequestContextUtils;
/**
* Resolves {@link HttpEntity} and {@link RequestEntity} method argument values,
* as well as return values of type {@link HttpEntity}, {@link ResponseEntity},
* and {@link ProblemDetail}.
* {@link ErrorResponse} and {@link ProblemDetail}.
*
* <p>An {@link HttpEntity} return type has a specific purpose. Therefore, this
* handler should be configured ahead of handlers that support any return
@@ -122,7 +123,7 @@ public class HttpEntityMethodProcessor extends AbstractMessageConverterMethodPro
public boolean supportsReturnType(MethodParameter returnType) {
Class<?> type = returnType.getParameterType();
return ((HttpEntity.class.isAssignableFrom(type) && !RequestEntity.class.isAssignableFrom(type)) ||
ProblemDetail.class.isAssignableFrom(type));
ErrorResponse.class.isAssignableFrom(type) || ProblemDetail.class.isAssignableFrom(type));
}
@Override
@@ -180,7 +181,10 @@ public class HttpEntityMethodProcessor extends AbstractMessageConverterMethodPro
ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);
HttpEntity<?> httpEntity;
if (returnValue instanceof ProblemDetail detail) {
if (returnValue instanceof ErrorResponse response) {
httpEntity = new ResponseEntity<>(response.getBody(), response.getHeaders(), response.getRawStatusCode());
}
else if (returnValue instanceof ProblemDetail detail) {
httpEntity = new ResponseEntity<>(returnValue, HttpHeaders.EMPTY, detail.getStatus());
}
else {

View File

@@ -52,6 +52,8 @@ import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.web.ErrorResponse;
import org.springframework.web.ErrorResponseException;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.annotation.RequestMapping;
@@ -129,6 +131,8 @@ public class HttpEntityMethodProcessorMockTests {
private MethodParameter returnTypeInt;
private MethodParameter returnTypeErrorResponse;
private MethodParameter returnTypeProblemDetail;
private ModelAndViewContainer mavContainer;
@@ -175,7 +179,8 @@ 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);
returnTypeErrorResponse = new MethodParameter(getClass().getMethod("handle6"), -1);
returnTypeProblemDetail = new MethodParameter(getClass().getMethod("handle7"), -1);
mavContainer = new ModelAndViewContainer();
servletRequest = new MockHttpServletRequest("GET", "/foo");
@@ -197,6 +202,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(returnTypeErrorResponse)).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();
@@ -282,6 +288,37 @@ public class HttpEntityMethodProcessorMockTests {
verify(stringHttpMessageConverter).write(eq(body), eq(accepted), isA(HttpOutputMessage.class));
}
@Test
public void shouldHandleErrorResponse() throws Exception {
ErrorResponseException ex = new ErrorResponseException(HttpStatus.BAD_REQUEST);
ex.getHeaders().add("foo", "bar");
servletRequest.addHeader("Accept", APPLICATION_PROBLEM_JSON_VALUE);
given(jsonMessageConverter.canWrite(ProblemDetail.class, APPLICATION_PROBLEM_JSON)).willReturn(true);
processor.handleReturnValue(ex, returnTypeProblemDetail, mavContainer, webRequest);
assertThat(mavContainer.isRequestHandled()).isTrue();
assertThat(webRequest.getNativeResponse(HttpServletResponse.class).getStatus()).isEqualTo(400);
verify(jsonMessageConverter).write(eq(ex.getBody()), eq(APPLICATION_PROBLEM_JSON), isA(HttpOutputMessage.class));
assertThat(ex.getBody()).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
ex.getBody().setInstance(URI.create("/something/else"));
processor.handleReturnValue(ex, returnTypeProblemDetail, mavContainer, webRequest);
assertThat(ex.getBody()).isNotNull()
.extracting(ProblemDetail::getInstance).isNotNull()
.extracting(URI::toString)
.as("Instance was not set to the request path")
.isEqualTo("/something/else");
}
@Test
public void shouldHandleProblemDetail() throws Exception {
ProblemDetail problemDetail = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
@@ -294,7 +331,7 @@ public class HttpEntityMethodProcessorMockTests {
assertThat(webRequest.getNativeResponse(HttpServletResponse.class).getStatus()).isEqualTo(400);
verify(jsonMessageConverter).write(eq(problemDetail), eq(APPLICATION_PROBLEM_JSON), isA(HttpOutputMessage.class));
assertThat(problemDetail).isNotNull()
assertThat(problemDetail)
.extracting(ProblemDetail::getInstance).isNotNull()
.extracting(URI::toString)
.as("Instance was not set to the request path")
@@ -842,7 +879,12 @@ public class HttpEntityMethodProcessorMockTests {
}
@SuppressWarnings("unused")
public ProblemDetail handle6() {
public ErrorResponse handle6() {
return null;
}
@SuppressWarnings("unused")
public ProblemDetail handle7() {
return null;
}