SpringBoot - 网络请求客户端WebClient使用详解6(异常处理、请求失败处理)
作者:hangge | 2019-12-18 08:10
七、请求异常处理
1,默认异常
(1)当我们使用 WebClient 发送请求时, 如果接口返回的不是 200 状态(而是 4xx、5xx 这样的异常状态),则会抛出 WebClientResponseException 异常。
@RestController
public class HelloController {
// 创建 WebClient 对象
private WebClient webClient = WebClient.builder()
.baseUrl("http://localhost:8080")
.build();
@GetMapping("/test")
public void test() {
Mono<String> mono = webClient
.get() // GET 请求
.uri("/xxxxx") // 请求一个不存在的路径
.retrieve() // 获取响应体
.bodyToMono(String.class);
System.out.println(mono.block());
}
}
(2)使用浏览器访问结果如下:

(3)使用 Postman 访问结果如下:

2,异常处理(适配所有异常)
(1)我们可以通过 doOnError 方法适配所有异常,比如下面代码在发生异常时将其转为一个自定义的异常抛出(这里假设使用 RuntimeException):
@RestController
public class HelloController {
// 创建 WebClient 对象
private WebClient webClient = WebClient.builder()
.baseUrl("http://localhost:8080")
.build();
@GetMapping("/test")
public void test() {
Mono<String> mono = webClient
.get() // GET 请求
.uri("/xxxxx") // 请求一个不存在的路径
.retrieve() // 获取响应体
.bodyToMono(String.class) //响应数据类型转换
.doOnError(WebClientResponseException.class, err -> {
System.out.println("发生错误:" +err.getRawStatusCode() + " "
+ err.getResponseBodyAsString());
throw new RuntimeException(err.getResponseBodyAsString());
});
System.out.println(mono.block());
}
}

(2)使用浏览器访问结果如下:

(3)使用 Postman 访问结果如下:

3,异常处理(适配指定异常)
(1)我们也可以通过 onStatus 方法根据 status code 来适配指定异常。下面代码同样在发生异常时将其转为一个自定义的异常抛出(这里假设使用 RuntimeException):
@RestController
public class HelloController {
// 创建 WebClient 对象
private WebClient webClient = WebClient.builder()
.baseUrl("http://localhost:8080")
.build();
@GetMapping("/test")
public void test() {
Mono<String> mono = webClient
.get() // GET 请求
.uri("/xxxxx") // 请求一个不存在的路径
.retrieve() // 获取响应体
.onStatus(e -> e.is4xxClientError(), resp -> {
System.out.println("发生错误:" + resp.statusCode().value() + " "
+ resp.statusCode().getReasonPhrase());
return Mono.error(new RuntimeException("请求失败"));
})
.onStatus(e -> e.is5xxServerError(), resp -> {
System.out.println("发生错误:" + resp.statusCode().value() + " "
+ resp.statusCode().getReasonPhrase());
return Mono.error(new RuntimeException("服务器异常"));
})
.bodyToMono(String.class); //响应数据类型转换
System.out.println(mono.block());
}
}

(2)使用 Postman 访问结果如下:

4,在发生异常时返回默认值
(1)我们可以使用 onErrorReturn 方法来设置个默认值,当请求发生异常是会使用该默认值作为响应结果。
@RestController
public class HelloController {
// 创建 WebClient 对象
private WebClient webClient = WebClient.builder()
.baseUrl("http://localhost:8080")
.build();
@GetMapping("/test")
public String test() {
Mono<String> mono = webClient
.get() // GET 请求
.uri("/xxxxx") // 请求一个不存在的路径
.retrieve() // 获取响应体
.bodyToMono(String.class)
.onErrorReturn("请求失败!!!"); // 失败时的默认值
return mono.block();
}
}
(2)使用浏览器访问结果如下:
全部评论(0)