Spring 5 Reactive - WebExceptionHandler is not getting called

感情迁移 提交于 2019-12-06 15:23:16

You can provide your own WebExceptionHandler, but you have to order it relatively to others, otherwise they might handle the error before yours get a chance to try.

  • the DefaultErrorWebExceptionHandler provided by Spring Boot for error handling (see reference documentation) is ordered at -1
  • the ResponseStatusExceptionHandler provided by Spring Framework is ordered at 0

So you can add @Order(-2) on your error handling component, to order it before the existing ones.

Alberto Galiana

An error response should have standard payload info. This can be done by extending AbstractErrorWebExceptionHandler

ErrorResponse: Data Class

data class ErrorResponse(
    val timestamp: String,
    val path: String,
    val status: Int,
    val error: String,
    val message: String
)

ServerResponseBuilder: 2 different methods to build an error response

  • default: handle standard errors
  • webClient: handle webClient exceptions (WebClientResponseException), not for this case

    class ServerResponseBuilder(
            private val request: ServerRequest, 
            private val status: HttpStatus) {
    
        fun default(): Mono<ServerResponse> =
            ServerResponse
                    .status(status)
                    .body(BodyInserters.fromObject(ErrorResponse(
                            Date().format(),
                            request.path(),
                            status.value(),
                            status.name,
                            status.reasonPhrase)))
    
        fun webClient(e: WebClientResponseException): Mono<ServerResponse> =
            ServerResponse
                    .status(status)
                    .body(BodyInserters.fromObject(ErrorResponse(
                            Date().format(),
                            request.path(),
                            e.statusCode.value(),
                            e.message.toString(),
                            e.responseBodyAsString)))
    }
    

GlobalErrorHandlerConfiguration: Error handler

@Configuration
@Order(-2)
class GlobalErrorHandlerConfiguration @Autowired constructor(
        errorAttributes: ErrorAttributes,
        resourceProperties: ResourceProperties,
        applicationContext: ApplicationContext,
        viewResolversProvider: ObjectProvider<List<ViewResolver>>,
        serverCodecConfigurer: ServerCodecConfigurer) :
        AbstractErrorWebExceptionHandler(
                errorAttributes,
                resourceProperties,
                applicationContext
        ) {

    init {
        setViewResolvers(viewResolversProvider.getIfAvailable { emptyList() })
        setMessageWriters(serverCodecConfigurer.writers)
        setMessageReaders(serverCodecConfigurer.readers)
    }

    override fun getRoutingFunction(errorAttributes: ErrorAttributes?): RouterFunction<ServerResponse> = 
        RouterFunctions.route(RequestPredicates.all(), HandlerFunction<ServerResponse> { response(it, errorAttributes) })

    private fun response(request: ServerRequest, errorAttributes: ErrorAttributes?): Mono<ServerResponse> =
        ServerResponseBuilder(request, status(request, errorAttributes)).default()

    private fun status(request: ServerRequest, errorAttributes: ErrorAttributes?) =
        HttpStatus.valueOf(errorAttributesMap(request, errorAttributes)["status"] as Int)

    private fun errorAttributesMap(request: ServerRequest, errorAttributes: ErrorAttributes?) =
        errorAttributes!!.getErrorAttributes(request, false)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!