Creating custom ErrorWebExceptionHandler fails

前端 未结 3 1642
无人共我
无人共我 2021-02-19 18:46

I am trying to create my own ErrorWebExceptionHandler in Spring Boot 2 by extending the default one but my application fails to start with the following message:

相关标签:
3条回答
  • 2021-02-19 19:15

    You need to set the messageWriters on that instance, because they are required here. You should probably create that as a @Bean, just like Spring Boot is doing in the dedicated auto-configuration.

    0 讨论(0)
  • 2021-02-19 19:23

    I just did this as well, and after looking at springs implementation I just added the components to the constructor.

    @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()
        })
    }
    
    0 讨论(0)
  • 2021-02-19 19:26

    Please try to add dependency of ServerCodecConfigurer in your constructor

    GlobalErrorWebExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ApplicationContext applicationContext, ServerCodecConfigurer configurer) { super(errorAttributes, resourceProperties, applicationContext); this.setMessageWriters(configurer.getWriters()); }

    0 讨论(0)
提交回复
热议问题