重写DefaultErrorAttributes的storeErrorInformation(Throwable error, ServerWebExchange exchange)方法,怎么获取http响应状态码
时间: 2024-03-01 19:52:31 浏览: 103
http响应状态码
要获取Http响应状态码,可以通过ServerWebExchange对象的getResponse()方法获取到响应对象,然后再通过响应对象的getStatusCode()方法获取到状态码。具体可以参考以下代码:
```java
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.reactive.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.server.ServerWebExchange;
import java.util.Map;
@Component
public class CustomErrorAttributes extends DefaultErrorAttributes {
@Override
public Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) {
Map<String, Object> errorAttributes = super.getErrorAttributes(request, options);
// 自定义错误属性
errorAttributes.put("custom", "custom");
return errorAttributes;
}
@Override
public void storeErrorInformation(Throwable error, ServerWebExchange exchange) {
super.storeErrorInformation(error, exchange);
// 获取响应状态码
HttpStatus httpStatus = exchange.getResponse().getStatusCode();
// 在控制台输出状态码
System.out.println("响应状态码:" + httpStatus.value());
// 在自定义的错误属性中添加状态码
exchange.getAttributes().put("status", httpStatus.value());
}
}
```
在以上代码中,重写了DefaultErrorAttributes的storeErrorInformation方法,通过ServerWebExchange对象获取到响应对象,再通过响应对象的getStatusCode()方法获取到状态码。然后将状态码添加到自定义的错误属性中,以便后续处理。
阅读全文