k94314517
2024-07-03 ca133ed72b297141f906810f81413e15d3d66333
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.doumee.config;
 
import com.doumee.core.exception.BusinessException;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
 
import java.nio.charset.StandardCharsets;
 
public class GlobalErrorFilter implements GlobalFilter {
 
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        return chain.filter(exchange).onErrorResume(throwable -> {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
 
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
 
            String errorMessage = "{\"message\": \"" + throwable.getMessage() + "\"}";
            byte[] bytes = errorMessage.getBytes(StandardCharsets.UTF_8);
            DataBufferFactory bufferFactory = response.bufferFactory();
            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return response.writeWith(Mono.just(bufferFactory.wrap(bytes)));
        });
    }
}