java - 如何处理渲染 View 时抛出的异常

标签 java spring jsp exception

对于处理请求时抛出的异常,Spring 有多种不同的方法来注册异常处理程序。当渲染 View 时抛出异常时,有没有办法应用类似的异常处理?至少我希望能够执行一些日志记录。

最佳答案

问题是 View 渲染期间抛出的异常不能做太多事情。特别是,它们通常无法呈现包含错误报告的 HTML 页面...甚至无法发送 5xx 响应...因为响应通常会在引发异常之前“提交”。

所以你能做的最好的(可能)是:

  • 为捕获并记录异常的 View 对象创建一个包装器,或者
  • 在 servlet 过滤器中进行日志记录,

但是 Web 容器很可能可以配置为记录未捕获的异常。

更新

I just noticed spring's HandlerInterceptor class exposes an 'afterCompletion' method which will be invoked when exceptions are thrown. Any thoughts as to the benefits of using this vs. a filter?

尝试一下看看。 :-) 但考虑到以下情况,我怀疑它是否有效。

Using a filter or interceptor does not work for exceptions thrown while rendering a jsp. It does print to err out:

Dec 16, 2012 12:18:03 PM org.apache.catalina.core.ApplicationDispatcher 
    invoke SEVERE: Servlet.service() for servlet jsp threw exception
    javax.el.PropertyNotFoundException: Property 'fooo' not found on 
    type java.lang.String" 

Unfortunately the exception is not propagated upwards to the filter. I'd like to add my own logging which sends out error notifications and logs additional information about the failed request. Keeping an eye on log files to spot errors isn't a good option.

  1. 日志消息很可能实际上是使用日志记录子系统生成的。如果是,您可以使用日志记录配置为 JSP 引擎日志记录事件添加您自己的处理程序并发送特殊通知。

  2. 事实上,异常是 1) 在 JSP View 渲染期间抛出的,2) JSP 引擎没有传播它们,这意味着(IMO)您不太可能有办法捕获它们。

  3. 另一个选项是为日志文件设置扫描程序...作为常规系统监控的一部分。

关于java - 如何处理渲染 View 时抛出的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13898644/

相关文章:

java - 使用 JmsTemplate 发送到 ActiveMQ 时出现文本消息编码问题

java - Tomcat 6.0 碧 Jade 异常

jsp - JSP中的iframe错误处理

java - 如果 jar 已经在运行,则阻止它运行?

java - mysql/java 字符集问题

java - 在后台加载图像、视频

java - Spring MVC Controller 映射未注册

Java SQL 数据库返回数据类型 Object 的结果

java - 我们可以为私有(private)类创建对象吗

java - Java中的数组索引问题