ResponseEntity为单独接口实现灵活返回值控制
2019-12-17 本文已影响0人
十毛tenmao
Restful API的Web后台服务,一般都提供了统一的接口规范。但是有时候又需要提供回调地址给外部服务,比如微信支付。那么这个回调接口的返回值需要满足微信支付回调的返回值协议(这个协议跟项目的Web后台服务不一致)。 利用ResponseEntity可以单独为某个接口实现返回值的完全控制,也不用修改项目的整体协议规范。
实现
- 项目的统一返回值协议
WebResult
/**
* @author timxia
* @since 2019/8/13
*/
@Getter
@Setter
@ToString
@NoArgsConstructor
public class WebResult<T> {
private static final int SUCCESS_CODE = 200;
private static final int SERVER_ERROR_CODE = 500;
private static final String SUCCESS_MSG = "操作成功";
private static final String ERROR_SERVER = "服务器繁忙,请稍后再试";
public static final WebResult<Void> SUCCESS_RESULT = new WebResult<>();
public static final WebResult<Void> SERVER_ERROR_RESULT = new WebResult<>(SERVER_ERROR_CODE, ERROR_SERVER);
/**
* 错误码.
*/
private int code = SUCCESS_CODE;
/**
* 错误信息.
*/
private String msg = SUCCESS_MSG;
/**
* 结果内容.
*/
private T data;
public WebResult(int code, String msg) {
this.code = code;
this.msg = msg;
}
public WebResult(T data) {
this.data = data;
}
}
- 返回不同的
HttpStatus
@RequestMapping("home")
@RestController
@SpringBootApplication
public class BootEntityApplication {
public static void main(String[] args) {
SpringApplication.run(BootEntityApplication.class, args);
}
@GetMapping("ping")
public WebResult<Void> ping() {
return WebResult.SUCCESS_RESULT;
}
/**
* 根据不同的异常情况,配置不同的HttpStatus
*/
@GetMapping("exception")
public ResponseEntity<WebResult> exception(int ex) {
try {
doWork(ex);
return ResponseEntity.ok(WebResult.SUCCESS_RESULT);
} catch (IllegalArgumentException e) {
//不同的异常设置不同的HttpStatus
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(new WebResult<>(400, e.getMessage()));
} catch (RuntimeException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(WebResult.SERVER_ERROR_RESULT);
}
}
private void doWork(int ex) {
switch (ex) {
case 0:
return;
case 1:
throw new IllegalArgumentException("bad request");
default:
throw new RuntimeException("服务器繁忙");
}
}
}
测试
# 没有异常HttpStatus=200
$ curl -i -X GET 'http://localhost:8080/home/exception?ex=0'
HTTP/1.1 200
Content-Type: application/json
Transfer-Encoding: chunked
Date: Tue, 17 Dec 2019 13:29:55 GMT
{"code":200,"msg":"操作成功","data":null,"success":true}
#参数异常HttpStatus=400
$ curl -i -X GET 'http://localhost:8080/home/exception?ex=1'
HTTP/1.1 400
Content-Type: application/json
Transfer-Encoding: chunked
Date: Tue, 17 Dec 2019 13:29:19 GMT
Connection: close
{"code":400,"msg":"bad request","data":null,"success":false}
#服务器异常HttpStatus=500
$ curl -i -X GET 'http://localhost:8080/home/exception?ex=2'
HTTP/1.1 500
Content-Type: application/json
Transfer-Encoding: chunked
Date: Tue, 17 Dec 2019 13:30:05 GMT
Connection: close
{"code":500,"msg":"服务器繁忙,请稍后再试","data":null,"success":false}
优点
- 使用
ResponseEntity
可以针对单个接口实现灵活的返回值控制,包括HttpStatus
- 如果在所有接口实现对某一个异常都设置统一的HttpStatus,可以使用
ExceptionHandler
- 使用HttpServletResponse也可以实现非常灵活的返回值控制,但是太底层了,不够面向对象,不建议使用