java~api返回值的標(biāo)準(zhǔn)化
api返回值的標(biāo)準(zhǔn)化
例如
{"status":200,"message":"操作成功","data":"{\"id\":1,\"name\":\"張三\"}"}
封裝返回對象
對象被封裝在base.util.ResponseUtils類型下,返回值是標(biāo)準(zhǔn)的ResponseEntity對象,返回體
進(jìn)行了二次封裝,主要有status,messsage和data組成,返回方法有ok和okMessage,如果
真是返回消息,不需要對象,可以選擇使用okMessage,反之使用ok方法。
封裝的返回對象:
@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
static class ResponseBody {
private int status;
private String message;
private Object data;
}
httpError和我們封裝的httpError
對于http error來說有很多種,基本可以定為code在400到500之間的,像客戶端參數(shù)問題就是400- bad request,而沒有認(rèn)證就是401-Unauthorized,認(rèn)證但沒有對應(yīng)的權(quán)限就是403-Forbidden,請求的
資源沒有發(fā)現(xiàn)就是404-Not Found,請求方式錯(cuò)誤(方法是post,你發(fā)起請求用了get)就是405- Method Not Allowed等。
- 使用標(biāo)準(zhǔn)http響應(yīng)狀態(tài)碼
@GetMapping(GET_HTTP_ERROR)
ResponseEntity<?> getHttpError() throws IOException {
return ResponseEntity.badRequest().build();
}
@Test
public void getHttpError() throws Exception {
mockMvc
.perform(
get(LindDemo.GET_HTTP_ERROR)
.accept(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().is(400));
}
響應(yīng)的結(jié)果
MockHttpServletResponse:
Status = 400
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
- 使用我們封裝的status狀態(tài)碼
@GetMapping(GET_ERROR)
ResponseEntity<?> getError() throws IOException {
return ResponseUtils.badRequest("傳入的參數(shù)非法!");
}
@Test
public void getError() throws Exception {
mockMvc
.perform(
get(LindDemo.GET_ERROR)
.accept(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
}
響應(yīng)的結(jié)果
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8
Body = {"status":400,"message":"傳入的參數(shù)非法!","data":{}}
Forwarded URL = null
Redirected URL = null
Cookies = []
通過上面的響應(yīng)結(jié)果可以看到,我們封裝的請求httpcode還是200,只不過把請求錯(cuò)誤400狀態(tài)碼寫在了body
對象里,目前這種方法用的比較多,像一些第三方接口用的都是這種方式,他們會(huì)規(guī)定相應(yīng)的響應(yīng)規(guī)范。
總結(jié)
事實(shí)上,兩種響應(yīng)體都沒有問題,關(guān)鍵在于開發(fā)之間的規(guī)則要確定,不要在項(xiàng)目里兩者兼用!
浙公網(wǎng)安備 33010602011771號