All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.guanmengyuan.config.handler.GlobalWebErrorHandler Maven / Gradle / Ivy

package com.guanmengyuan.config.handler;

import com.guanmengyuan.config.attributes.GlobalErrorAttributes;
import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.AbstractErrorWebExceptionHandler;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.*;
import reactor.core.publisher.Mono;

import java.util.Map;

@Configuration
@Order(-2)
public class GlobalWebErrorHandler extends AbstractErrorWebExceptionHandler {

    public GlobalWebErrorHandler(GlobalErrorAttributes globalErrorAttributes,
                                 ApplicationContext applicationContext, ServerCodecConfigurer serverCodecConfigurer) {
        super(globalErrorAttributes, new WebProperties().getResources(), applicationContext);
        super.setMessageReaders(serverCodecConfigurer.getReaders());
        super.setMessageWriters(serverCodecConfigurer.getWriters());
    }

    @Override
    protected RouterFunction getRoutingFunction(ErrorAttributes errorAttributes) {
        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
    }

    private Mono renderErrorResponse(ServerRequest request) {

        final Map errorPropertiesMap = getErrorAttributes(request, ErrorAttributeOptions.defaults());
        Object statusCode = errorPropertiesMap.get("httpStatusCode");
        errorPropertiesMap.remove("httpStatusCode");
        return ServerResponse.status((HttpStatusCode) statusCode)
                .contentType(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromValue(errorPropertiesMap));
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy