【发布时间】:2017-01-23 21:06:15
【问题描述】:
我想从控制器建议方面抛出一个标准的自定义异常,但由于某种原因,我的自定义异常没有被 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 如何处理异常的任何信息?
【问题讨论】:
-
你是否在测试中使用
SpringJUnit4ClassRunnerrunner? -
@ChrisThompson,是的,刚刚更新了测试
-
在测试中您要求
/exception,但日志显示path=/creditcards/,所以也许您正在查看日志的错误部分?还是路由不正确? -
@tonakai,对不起...我已经复制/粘贴/修改了,忘记修改日志了。
-
@PauChorro 没用
标签: java spring spring-mvc spring-boot