Spring-如何处理异常

发布于 2024-09-27 15:37:58 字数 601 浏览 2 评论 0原文

我正在使用 Spring 和 Velocity。有时速度会产生异常,例如

插入字符串文字时出错:org.apache.velocity.exception.MethodInitationException:在类 org.springframework.web.servlet.support.RequestContext 中调用方法“getMessage”引发异常类 org.springframework.context.NoSuchMessageException:否在区域设置“en_US”的代码“XX”下找到消息。

问题是 - 我可以指示 spring 抑制 NoSuchMessageException 吗?我对 Spring 很陌生,所以不知道是否可以创建一个异常处理程序,如果找不到消息,它不会抛出异常?在我的用例中,这是在 messages.properties 文件中找不到某些消息的有效用例。

[编辑] - 我找到了一种方法 org.apache.velocity.app.event.MethodExceptionEventHandler 为速度提供偶数处理程序。然而我不知道如何向 Spring 注册它。

I am using Spring with Velocity. At times velocity produces an exception like

Error in interpolating string literal : org.apache.velocity.exception.MethodInvocationException: Invocation of method 'getMessage' in class org.springframework.web.servlet.support.RequestContext threw exception class org.springframework.context.NoSuchMessageException : No message found under code 'XX' for locale 'en_US'.

Question is - can I instruct spring to suppress NoSuchMessageException ? I am pretty new to Spring so do not know if I can create a exception handler which will not throw a exception if the message is not found? In my use case, it is a valid use case of not finding some of the messages in the messages.properties file.

[EDIT] - I found a way org.apache.velocity.app.event.MethodExceptionEventHandler to supply an even handler to velocity. I am however not sure how to register it with Spring.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

Bonjour°[大白 2024-10-04 15:37:58

我认为,最好直接解决问题,而不是试图抑制异常,因为这可能会导致避免行为和未完成的操作。

但是,您没有告诉我们在未为给定代码定义消息的情况下您希望系统如何响应。您想要一个空白字符串,还是应该将代码本身用作默认消息?

我假设在 Spring 上下文中的某个地方定义了某种 messageSource bean。这些 MessageSource bean 通常具有属性 useCodeAsDefaultMessage。默认为 false,但当设置为 true 时,在未定义消息的情况下,它们将返回代码本身作为消息。

或者,您可以子类化 MessageSource 类(无论您使用哪个类),并重写 getDefaultMessage() 方法来处理无法解析代码的情况。

It would be better, I think, to address the problem directly, rather than trying to suppress the exception, which could lead to avoid behaviour and uncompleted operations.

However, you didn't tell us how you'd want the system to respond in cases where the message is not defined for a given code. Do you want a blank String, or should the code itself be used as the default message?

I'm assuming that somewhere in your Spring context you have a defined a messageSource bean of some sort. These MessageSource beans usually have a property useCodeAsDefaultMessage. This defaults to false, but when set to true they will return the code itself as the message, in cases where no message is defined.

Alternatively, you can subclass the MessageSource class (whichever one you're using), and override the getDefaultMessage() method to handle cases where the code cannot be resolved.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文