#342 - Augment error message when building link without a web request.

We now explicitly check whether we could look up request attributes and throw an exception with a message indicating the cause of the failure.

Original pull request: #344.
This commit is contained in:
Greg Turnquist
2015-05-18 11:17:10 -05:00
committed by Oliver Gierke
parent 4c2c6d5a4a
commit b592ddda92
2 changed files with 43 additions and 3 deletions

View File

@@ -17,11 +17,10 @@ package org.springframework.hateoas.mvc;
import static org.springframework.util.StringUtils.*;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.net.URI;
import javax.servlet.http.HttpServletRequest;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.core.AnnotationMappingDiscoverer;
import org.springframework.hateoas.core.DummyInvocationUtils;
@@ -237,7 +236,7 @@ public class ControllerLinkBuilder extends LinkBuilderSupport<ControllerLinkBuil
private static HttpServletRequest getCurrentRequest() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
Assert.state(requestAttributes != null, "Could not find current request via RequestContextHolder");
Assert.state(requestAttributes != null, "Could not find current request via RequestContextHolder. Is this being called from a Spring MVC handler?");
Assert.isInstanceOf(ServletRequestAttributes.class, requestAttributes);
HttpServletRequest servletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
Assert.state(servletRequest != null, "Could not find current HttpServletRequest");

View File

@@ -0,0 +1,41 @@
package org.springframework.hateoas.mvc;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.*;
import org.junit.Before;
import org.junit.Test;
import org.springframework.web.context.request.RequestContextHolder;
/**
* Test cases for {@link ControllerLinkBuilder} that are NOT inside an existing Spring MVC request
*
* @author Greg Turnquist
*/
public class ControllerLinkBuilderOutsideSpringMvcUnitTest {
/**
* Clear out any existing request attributes left behind by other tests
*/
@Before
public void setUp() {
RequestContextHolder.setRequestAttributes(null);
}
/**
* @see #342
*/
@Test(expected = IllegalStateException.class)
public void createsLinkToMethodOnParameterizedControllerRoot() {
try {
linkTo(methodOn(ControllerLinkBuilderUnitTest.PersonsAddressesController.class, 15)
.getAddressesForCountry("DE")).withSelfRel();
} catch (IllegalStateException e) {
assertThat(e.getMessage(), equalTo("Could not find current request via RequestContextHolder. Is this being called from a Spring MVC handler?"));
throw e;
}
}
}