【发布时间】:2020-03-23 21:50:39
【问题描述】:
我正在使用 spring webflux 开发服务。我使用@ControllerAdvice 实现了异常处理。它工作得很好,但是当我运行集成测试时,似乎没有加载 @ControllerAdvice 带注释的组件,导致这个响应:
{
"timestamp":"2019-11-28T08:56:47.285+0000",
"path":"/fooController/bar",
"status":500,
"error":"Internal Server Error",
"message":"java.lang.IllegalStateException: Could not resolve parameter [1] in protected org.springframework.http.ResponseEntity<it.test.model.Response> it.test.exception.ExceptionHandlerController.handleServiceException(java.lang.Exception,org.springframework.web.context.request.WebRequest): No suitable resolver
}
这是我的控制器建议:
@ControllerAdvice
public class ExceptionHandlerController extends ResponseEntityExceptionHandler {
private final Logger logger = LoggerFactory.getLogger(ExceptionHandlerController.class);
@ExceptionHandler
protected ResponseEntity<Response> handleServiceException(Exception ex, WebRequest request) {
this.logger.error("Error occurred: \"{}\"", ex.getMessage());
Response<Foo> response = new Response<>(new Foo(),
"generic error",
HttpStatus.INTERNAL_SERVER_ERROR);
return new ResponseEntity<>(response, null, HttpStatus.OK);
}
}
这是我的集成测试类
@ExtendWith(SpringExtension.class)
@WebFluxTest(MyController.class)
@ContextConfiguration(classes = {MyController.class, MyServiceImpl.class, ExceptionHandlerController.class })
public class MyControllerIT {
@Autowired
private WebTestClient webTestClient;
@Test
public void testShouldFail() throws IOException {
return this.webTestClient.get()
.uri(uri)
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isOk()
.expectBody()
.jsonPath("$.statusCode").isEqualTo(500);
}
}
【问题讨论】:
-
如果出现错误,您永远不应该返回 HttpStatus.OK。那是糟糕的设计
-
请您删除
@ContextConfiguration(classes = {MyController.class, MyServiceImpl.class, ExceptionHandlerController.class }) -
意思应该是:http response 200 因为错误被管理所以执行已经成功处理。里面的statusCode表示发生了en错误
-
如果我删除@ContextConfiguration spring 不会启动
标签: java spring spring-boot spring-cloud spring-webflux