在创建bean时抛出异常的优雅处理 [英] Graceful handling of exception thrown while creating beans

查看:133
本文介绍了在创建bean时抛出异常的优雅处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我希望我的Spring MVC Web应用程序能够优雅地处理在创建bean时抛出的特定类型的异常。一个外部文件。如果配置数据有问题,我的一个bean构造函数会抛出特定类型的异常。由于问题的原因是错误的配置文件,我希望我的Web应用程序使用有用的日志消息和/或错误页面进行响应,而不是抛出异常的堆栈跟踪。所以我想我需要一些异常处理程序连接到IOC容器或调度程序servlet。我该怎么做?



只是为了清楚。我正在询问servlet正在初始化时抛出的异常,而不是处理HTTP请求,因此控制器上的 @ExceptionHandler 注释是无用的。

解决方案

我通过引入一个间接级别来解决这个难题。我的豆子真的只是一个句柄。如果配置文件不正确,则该bean捕获异常,记录一条消息,并注意到读取失败。稍后访问bean会抛出一个合适的异常。


I want my Spring MVC web app to gracefully handle a particular type of exception thrown while creating the beans.

The construction of one of my beans reads configuration data from an external file. If that configuration data is faulty, one of my bean constructors will throw an exception of a particular type. As the cause of the problem would be a faulty configuration file, I want my web application to respond with a useful log message and/or an error page, rather than a stack-trace of the thrown exception. So I guess I need some kind of exception handler hooked into the IOC container or dispatcher servlet. How can I do that?

Just to be clear. I'm asking about exceptions thrown as the servlet is initialising, not as it handles HTTP requests, so @ExceptionHandler annotations on controllers are not useful.

解决方案

I worked around this difficulty by introducing a level of indirection. My bean is really just a handle. If the configuration file is bad, the bean catches the exception, logs a message, and notes that reading failed. Accessing the bean later then throws a suitable exception.

这篇关于在创建bean时抛出异常的优雅处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆