将参数传递给 Grails 异常处理程序
Passing parameters to a Grails exception handler
我在同一个控制器中有几个方法可以显式捕获相同的异常,所以我愿意用 Grails 异常处理程序替换它们,但是我 运行 遇到了一个问题:每个控制器中的 catch 块记录一条带有调用上下文的消息,如下所示:
catch (WhateverException e) {
response.status = HttpStatus.PROPER_HTTP_STATUS
log.info("A whatever error occurred. Context = ${[foo: request.foo, bar: request.baz]}")
}
事实是,即使捕获的异常相同,每个控制器操作的上下文内容也不同。
有没有办法将上下文作为参数传递给 whateverException
异常处理程序,以便从每个操作中删除显式 catch 块?
Grails 不直接允许这样做。
我还有一些想法要给你:
- 使用 SLF4Js Message Diagnostic Context (MDC). Populate it inside the controller method that the exception is thrown in. Make sure that the MDC is included in the logback encoder (e.g. the
PatternLayoutEncoder
therefore offers a %X
). Or even use a Grails interceptor 使用所有请求通用的参数填充 MDC。
- 您也可以在 Grails 异常处理程序 方法中访问
request
属性。如果要记录的请求属性总是相同的,只是它们的值不同,那将是最简单的解决方案
- 如果您的 Grails 控制器是 prototype-scoped,您可以将上下文分配给控制器字段并在异常处理程序中访问它。可能不是最好的解决方案。
- 考虑一下您的 异常是否不能 'capture the context' 并将其存储在其自己的字段之一中 .
我经常构造这样的异常:
class MyException extends RuntimeException {
final int field1
final String field2
MyException(int field1, String field2) {
super("a message that includes $field1 and $field2")
this.field1 = field1
this.field2 = field2
}
}
这样,上下文 (field1
、field2
) 也可以在异常处理程序中访问。
我在同一个控制器中有几个方法可以显式捕获相同的异常,所以我愿意用 Grails 异常处理程序替换它们,但是我 运行 遇到了一个问题:每个控制器中的 catch 块记录一条带有调用上下文的消息,如下所示:
catch (WhateverException e) {
response.status = HttpStatus.PROPER_HTTP_STATUS
log.info("A whatever error occurred. Context = ${[foo: request.foo, bar: request.baz]}")
}
事实是,即使捕获的异常相同,每个控制器操作的上下文内容也不同。
有没有办法将上下文作为参数传递给 whateverException
异常处理程序,以便从每个操作中删除显式 catch 块?
Grails 不直接允许这样做。
我还有一些想法要给你:
- 使用 SLF4Js Message Diagnostic Context (MDC). Populate it inside the controller method that the exception is thrown in. Make sure that the MDC is included in the logback encoder (e.g. the
PatternLayoutEncoder
therefore offers a%X
). Or even use a Grails interceptor 使用所有请求通用的参数填充 MDC。 - 您也可以在 Grails 异常处理程序 方法中访问
request
属性。如果要记录的请求属性总是相同的,只是它们的值不同,那将是最简单的解决方案 - 如果您的 Grails 控制器是 prototype-scoped,您可以将上下文分配给控制器字段并在异常处理程序中访问它。可能不是最好的解决方案。
- 考虑一下您的 异常是否不能 'capture the context' 并将其存储在其自己的字段之一中 .
我经常构造这样的异常:
class MyException extends RuntimeException {
final int field1
final String field2
MyException(int field1, String field2) {
super("a message that includes $field1 and $field2")
this.field1 = field1
this.field2 = field2
}
}
这样,上下文 (field1
、field2
) 也可以在异常处理程序中访问。