Skip to content

网关异常处理程序

系列HTTP 状态序列HTTP 状态值原因
CLIENT_ERROR4404Not Found
SERVER_ERROR5503Service Unavailable
java
package cloud.xuxiaowei.gateway.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * 网关异常 处理程序
 *
 * @author xuxiaowei
 * @since 0.0.1
 */
@Setter
@Slf4j
@Component
public class GatewayErrorWebExceptionHandler implements ErrorWebExceptionHandler, Ordered {

    public static final int ORDERED = Ordered.HIGHEST_PRECEDENCE + 10000;

    private int order = ORDERED;

    @Override
    public int getOrder() {
        return this.order;
    }

    @NonNull
    @Override
    public Mono<Void> handle(@NonNull ServerWebExchange exchange, @NonNull Throwable ex) {

        ServerHttpResponse response = exchange.getResponse();

        log.error("网关异常处理器:", ex);

        Map<String, Object> map = new HashMap<>(4);

        if (ex instanceof ResponseStatusException) {
            ResponseStatusException responseStatusException = (ResponseStatusException) ex;

            HttpStatus status = responseStatusException.getStatus();

            if (status == HttpStatus.NOT_FOUND) {
                // 404 Not Found
                map.put("code", HttpStatus.NOT_FOUND.value());
                map.put("msg", "访问地址不存在");
            }
            else if (status == HttpStatus.SERVICE_UNAVAILABLE) {
                // 503 Service Unavailable
                map.put("code", HttpStatus.SERVICE_UNAVAILABLE.value());
                map.put("msg", "服务不可用,请稍后再试或联系管理员");
            }
            else {
                map.put("msg", String.format("未处理异常状态:%s,请联系管理员", status.value()));
            }
        }
        else {
            map.put("msg", "未判断异常类型,请联系管理员");
        }

        return writeWith(response, map);
    }

    /**
     * 使用 Mono 响应数据
     * @param response 响应
     * @param object 数据
     * @return 返回 响应结果
     */
    @SneakyThrows
    @SuppressWarnings({ "deprecation" })
    public static Mono<Void> writeWith(@NonNull ServerHttpResponse response, Object object) {

        // 响应状态码
        response.setStatusCode(HttpStatus.OK);

        // 不可使用 APPLICATION_JSON(部分浏览器会乱码)
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());

        byte[] bytes = objectMapper.writeValueAsBytes(object);

        DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(dataBuffer));
    }

}
java
package cloud.xuxiaowei.gateway.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * 网关异常 处理程序
 *
 * @author xuxiaowei
 * @since 0.0.1
 */
@Setter
@Slf4j
@Component
public class GatewayErrorWebExceptionHandler implements ErrorWebExceptionHandler, Ordered {

    public static final int ORDERED = Ordered.HIGHEST_PRECEDENCE + 10000;

    private int order = ORDERED;

    @Override
    public int getOrder() {
        return this.order;
    }

    @NonNull
    @Override
    public Mono<Void> handle(@NonNull ServerWebExchange exchange, @NonNull Throwable ex) {

        ServerHttpResponse response = exchange.getResponse();

        log.error("网关异常处理器:", ex);

        Map<String, Object> map = new HashMap<>(4);

        if (ex instanceof ResponseStatusException responseStatusException) {

            HttpStatusCode statusCode = responseStatusException.getStatusCode();

            if (statusCode == HttpStatus.NOT_FOUND) {
                // 404 Not Found
                map.put("code", HttpStatus.NOT_FOUND.value());
                map.put("msg", "访问地址不存在");
            }
            else if (statusCode == HttpStatus.SERVICE_UNAVAILABLE) {
                // 503 Service Unavailable
                map.put("code", HttpStatus.SERVICE_UNAVAILABLE.value());
                map.put("msg", "服务不可用,请稍后再试或联系管理员");
            }
            else {
                map.put("msg", String.format("未处理异常状态:%s,请联系管理员", statusCode.value()));
            }
        }
        else {
            map.put("msg", "未判断异常类型,请联系管理员");
        }

        return writeWith(response, map);
    }

    /**
     * 使用 Mono 响应数据
     * @param response 响应
     * @param object 数据
     * @return 返回 响应结果
     */
    @SneakyThrows
    @SuppressWarnings({ "deprecation" })
    public static Mono<Void> writeWith(@NonNull ServerHttpResponse response, Object object) {

        // 响应状态码
        response.setStatusCode(HttpStatus.OK);

        // 不可使用 APPLICATION_JSON(部分浏览器会乱码)
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());

        byte[] bytes = objectMapper.writeValueAsBytes(object);

        DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(dataBuffer));
    }

}