Feature/gh 1283 exception (#1458)

* wrap errors in NativeEnvironmentRepository
This commit is contained in:
Nicolas Homble
2019-11-18 10:26:43 -05:00
committed by Ryan Baxter
parent cfe60db520
commit 3d635f1488
7 changed files with 116 additions and 5 deletions

View File

@@ -275,6 +275,12 @@ public class EnvironmentController {
response.sendError(HttpStatus.BAD_REQUEST.value());
}
@ExceptionHandler(EnvironmentException.class)
public void environmentException(HttpServletResponse response, EnvironmentException e)
throws IOException {
response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
}
private void validateProfiles(String profiles) {
if (profiles.contains("-")) {
throw new IllegalArgumentException(

View File

@@ -0,0 +1,33 @@
/*
* Copyright 2015-2019 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.config.server.environment;
/**
* @author Nicolas Homble
*/
@SuppressWarnings("serial")
public class EnvironmentException extends RuntimeException {
public EnvironmentException(String string) {
super(string);
}
public EnvironmentException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright 2015-2019 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.config.server.environment;
/**
* @author Nicolas Homble
*
*/
@SuppressWarnings("serial")
public class FailedToConstructEnvironmentException extends EnvironmentException {
public FailedToConstructEnvironmentException(String string) {
super(string);
}
public FailedToConstructEnvironmentException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@@ -36,6 +36,7 @@ import org.springframework.boot.context.config.ConfigFileApplicationListener;
import org.springframework.cloud.config.environment.Environment;
import org.springframework.cloud.config.environment.PropertySource;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.NestedExceptionUtils;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
@@ -145,14 +146,19 @@ public class NativeEnvironmentRepository
// log levels in the caller)
builder.application()
.setListeners(Arrays.asList(new ConfigFileApplicationListener()));
ConfigurableApplicationContext context = builder.run(args);
environment.getPropertySources().remove("profiles");
try {
try (ConfigurableApplicationContext context = builder.run(args)) {
environment.getPropertySources().remove("profiles");
return clean(new PassthruEnvironmentRepository(environment).findOne(config,
profile, label, includeOrigin));
}
finally {
context.close();
catch (Exception e) {
String msg = String.format(
"Could not construct context for config=%s profile=%s label=%s includeOrigin=%b",
config, profile, label, includeOrigin);
String completeMessage = NestedExceptionUtils.buildMessage(msg,
NestedExceptionUtils.getMostSpecificCause(e));
throw new FailedToConstructEnvironmentException(completeMessage, e);
}
}

View File

@@ -31,11 +31,14 @@ import org.springframework.cloud.config.environment.Environment;
import org.springframework.cloud.config.environment.PropertySource;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -612,4 +615,17 @@ public class EnvironmentControllerTests {
}
@Test
public void handleEnvironmentException() throws Exception {
when(repository.findOne(eq("exception"), eq("bad-syntax.ext"), any(), eq(false)))
.thenThrow(new FailedToConstructEnvironmentException("Cannot construct",
new RuntimeException("underlier")));
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller)
.setControllerAdvice(controller).build();
MvcResult result = mvc
.perform(MockMvcRequestBuilders.get("/exception/bad-syntax.ext"))
.andExpect(MockMvcResultMatchers.status().is(500)).andReturn();
assertThat(result.getResponse().getErrorMessage()).isEqualTo("Cannot construct");
}
}

View File

@@ -26,6 +26,7 @@ import org.springframework.cloud.config.server.environment.SearchPathLocator.Loc
import org.springframework.context.ConfigurableApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Dave Syer
@@ -219,4 +220,17 @@ public class NativeEnvironmentRepositoryTests {
.get(0).getSource().get("foo")).isEqualTo("test_bar");
}
@Test
public void duplicateYamlKeys() {
this.repository.setSearchLocations("classpath:/test/bad-syntax");
NativeEnvironmentRepository repo = this.repository;
assertThatExceptionOfType(FailedToConstructEnvironmentException.class)
.isThrownBy(() -> repo.findOne("foo", "master", "default")).withMessage(
"Could not construct context for config=foo profile=master label=default includeOrigin=false; nested exception is while constructing a mapping\n"
+ " in 'reader', line 1, column 1:\n" + " key: value\n"
+ " ^\n" + "found duplicate key key\n"
+ " in 'reader', line 2, column 1:\n" + " key: value\n"
+ " ^\n");
}
}

View File

@@ -0,0 +1,2 @@
key: value
key: value