package cn.qinys.platform.gateway.config;


import cn.qinys.platform.gateway.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.webflux.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关错误异常配置类
 *
 * @author v-lishiquan.gx@chinatelecom.cn
 * @date 2020-09-03
 */
@Configuration
@Slf4j
public class GlobalExceptionConfiguration implements ErrorWebExceptionHandler, Ordered {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();
        if (response.isCommitted()) {
            return Mono.error(ex);
        }
        // header set_json响应
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        //是否响应状态异常
        if (ex instanceof ResponseStatusException rse) {
            response.setStatusCode(rse.getStatusCode());
        }
        logger.error("服务器异常 == {}", ex.getMessage());
        return Result.fail(response, 500, ex.getMessage());

    }

    @Override
    public int getOrder() {
        return -1;
    }
}
