java Spring引导未使用@ControllerAdvice覆盖异常
我想从控制器建议方面抛出一个标准的自定义异常,但由于某些原因,我的自定义异常没有被spring boot(1.3.3-RELEASE)捕获
这是我的代码:
我的测试
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(MyApplication.class)
@WebIntegrationTest("server.port:9000")
public class ControllerTest {
private final String URL = "http://localhost:9000";
@Test
public void testCustomExceptionResponse() {
// Invoke my controller generating some exception
Map error = restTemplate.getForObject(URL+"/exception/", Map.class);
assertTrue(error.get("exception").contains("MyCustomException"));
}
}
控制器
@RequestMapping(value = "/", method = RequestMethod.GET)
public List<Object> findAll() throws Exception {
// generate whatever exception here
if (1<2) throw new IllegalIdentifierException("test whatever exception");
return ccRepository.findByActive(true);
}
用@ControllerAdvice注释的GlobalExceptionHandler
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
// Catch whatever exception to throw my custom exception
@ExceptionHandler(Exception.class)
public void handleException(Exception ex) throws Exception {
logger.error("Exception Occured: ", ex);
throw new MyCustomException(ex.getLocalizedMessage());
}
}
我已经调试了代码,正在执行handleException方法,但是奇怪的是,正在抛出MyCustomException,但控制器响应返回了抛出的原始异常:
{timestamp=1473963128439, status=500, error=Internal Server Error, exception=org.hibernate.metamodel.relational.IllegalIdentifierException, message=test whatever exception, path=/exception/}
我希望有这样的东西:
exception=com.myapp.MyCustomException
据我所知,控制器建议是捕获控制器中所有异常的通用方法,以绑定一些逻辑(在我的例子中是记录器),然后我使用自定义异常定制意外异常
我是否遗漏了Spring Boot如何处理异常的内容
# 1 楼答案
这并不是ControllerAdvice的目的
发生了什么事
你该怎么办
控制器建议用于在发生错误时返回有效的Http响应
例如,您可以将其更改为:
因此:
您可以使用
MockMvc
测试它:# 2 楼答案
我刚刚根据您的代码创建了一个示例项目,请尝试更改此行:
到
由于您的
RequestMapping
正在查找/
,我认为其他方法正在处理您的http请求,这也解释了hibernate错误消息,因为1<2
始终返回true我的日志如下所示: