创建自定义ErrorWebExceptionHandler失败

时间:2018-09-25 12:08:40

标签: spring-boot spring-webflux

我正在尝试通过扩展默认启动名在Spring Boot 2中创建自己的ErrorWebExceptionHandler,但是我的应用程序无法以以下消息开头:

Caused by: java.lang.IllegalArgumentException: Property 'messageWriters' is required
at org.springframework.boot.autoconfigure.web.reactive.error.AbstractErrorWebExceptionHandler.afterPropertiesSet(AbstractErrorWebExceptionHandler.java:214) ~[spring-boot-autoconfigure-2.0.4.RELEASE.jar:2.0.4.RELEASE]

我的处理程序(科特琳代码):

@Component
@Order(-2)
class SampleErrorWebExceptionHandler(
    errorAttributes: ErrorAttributes?,
    resourceProperties: ResourceProperties?,
    errorProperties: ErrorProperties?,
    applicationContext: ApplicationContext?
) : DefaultErrorWebExceptionHandler(errorAttributes, resourceProperties, errorProperties, applicationContext) {

    override fun logError(request: ServerRequest, errorStatus: HttpStatus) {
        // do something
    }
}

可能是什么原因?

3 个答案:

答案 0 :(得分:5)

您需要在该实例上设置messageWriters,因为此处是必需的。您可能应该将其创建为@Bean,就像Spring Boot is doing in the dedicated auto-configuration一样。

答案 1 :(得分:1)

我也这样做了,在查看springs实现之后,我只是将组件添加到了构造函数中。

@Component
@Order(-2)
class GlobalErrorWebExceptionHandler(
        errorAttributes: ErrorAttributes,
        resourceProperties: ResourceProperties,
        applicationContext: ApplicationContext,
        viewResolvers: ObjectProvider<ViewResolver>,
        serverCodecConfigurer: ServerCodecConfigurer
) : AbstractErrorWebExceptionHandler(
        errorAttributes,
        resourceProperties,
        applicationContext
) {
    private val logger = LogFactory.getLog(GlobalErrorWebExceptionHandler::class.java)!!

    init {
        setViewResolvers(viewResolvers.orderedStream().collect(Collectors.toList()))
        setMessageWriters(serverCodecConfigurer.writers)
        setMessageReaders(serverCodecConfigurer.readers)
    }

    override fun getRoutingFunction(errorAttributes: ErrorAttributes) = RouterFunctions.route(RequestPredicates.all(), HandlerFunction { request ->
        val ex = getError(request)
        logger.error(ex.message)

        ServerResponse.ok().build()
    })
}

答案 2 :(得分:0)

请尝试在构造函数中添加ServerCodecConfigurer的依赖项

use_count