Skip to content

Instantly share code, notes, and snippets.

@benoit74
Last active November 27, 2018 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benoit74/651a9348120613e42b0e2ee4894a6e5e to your computer and use it in GitHub Desktop.
Save benoit74/651a9348120613e42b0e2ee4894a6e5e to your computer and use it in GitHub Desktop.
/*
* Copyright 2002-2015 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
*
* http://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 ch.octo.test.controlleradvice;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
import org.junit.Test;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Exception handling via {@code @ExceptionHandler} method.
*
* @author Rossen Stoyanchev
*/
public class ExceptionHandlerTests {
@Test
public void testExceptionHandlerMethod() throws Exception {
standaloneSetup(new PersonController()).build()
.perform(get("/person/Clyde"))
.andExpect(status().isOk())
.andExpect(forwardedUrl("errorView"));
}
@Test
public void testGlobalExceptionHandlerMethod() throws Exception {
standaloneSetup(new PersonController()).setControllerAdvice(new GlobalExceptionHandler()).build()
.perform(get("/person/Bonnie"))
.andExpect(status().isOk())
.andExpect(forwardedUrl("globalErrorView"));
}
@Controller
private static class PersonController {
@RequestMapping(value="/person/{name}", method=RequestMethod.GET)
public String show(@PathVariable String name) {
if (name.equals("Clyde")) {
throw new IllegalArgumentException("simulated exception");
}
else if (name.equals("Bonnie")) {
throw new IllegalStateException("simulated exception");
}
return "person/show";
}
@ExceptionHandler
public String handleException(IllegalArgumentException exception) {
return "errorView";
}
}
@ControllerAdvice
private static class GlobalExceptionHandler {
@ExceptionHandler
public String handleException(IllegalStateException exception) {
return "globalErrorView";
}
}
}
package ch.octo.test.controlleradvice;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
public class GenericControllerAdviceTests {
@Test
public void testGenericControllerAdviceMethod() throws Exception {
MockHttpServletResponse response = standaloneSetup(new PersonController())
.setControllerAdvice(new DeprecatedControllerAdvice())
.build()
.perform(get("/person").accept(MediaType.APPLICATION_JSON))
.andReturn().getResponse();
Assert.assertEquals(HttpStatus.OK.value(), response.getStatus());
Assert.assertTrue(response.getHeaderNames().contains("Warning"));
Assert.assertEquals("299 - Deprecated Endpoint", response.getHeader("Warning"));
}
@Controller
private static class PersonController {
@RequestMapping(value="/person", method=RequestMethod.GET)
public String show() {
return "whatever";
}
}
@ControllerAdvice
private static class DeprecatedControllerAdvice implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
response.getHeaders().add("Warning", "299 - Deprecated Endpoint");
return body;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment