例如json
{"status":200,"message":"操做成功","data":"{\"id\":1,\"name\":\"張三\"}"}
對象被封裝在base.util.ResponseUtils類型下,返回值是標準的ResponseEntity對象,返回體
進行了二次封裝,主要有status
,messsage
和data
組成,返回方法有ok和okMessage,若是
真是返回消息,不須要對象,能夠選擇使用okMessage
,反之使用ok
方法。api
封裝的返回對象:app
@Builder @Getter @NoArgsConstructor @AllArgsConstructor static class ResponseBody { private int status; private String message; private Object data; }
對於http error來講有不少種,基本能夠定爲code在400到500之間的,像客戶端參數問題就是400- bad request
,而沒有認證就是401-Unauthorized
,認證但沒有對應的權限就是403-Forbidden
,請求的
資源沒有發現就是404-Not Found
,請求方式錯誤(方法是post,你發起請求用了get)就是405- Method Not Allowed
等。post
@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)); }
響應的結果ui
MockHttpServletResponse: Status = 400 Error message = null Headers = {} Content type = null Body = Forwarded URL = null Redirected URL = null Cookies = []
@GetMapping(GET_ERROR) ResponseEntity<?> getError() throws IOException { return ResponseUtils.badRequest("傳入的參數非法!"); } @Test public void getError() throws Exception { mockMvc .perform( get(LindDemo.GET_ERROR) .accept(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()); }
響應的結果code
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":"傳入的參數非法!","data":{}} Forwarded URL = null Redirected URL = null Cookies = []
經過上面的響應結果能夠看到,咱們封裝的請求httpcode仍是200,只不過把請求錯誤400狀態碼寫在了body
對象裏,目前這種方法用的比較多,像一些第三方接口用的都是這種方式,他們會規定相應的響應規範。orm
事實上,兩種響應體都沒有問題,關鍵在於開發之間的規則要肯定,不要在項目裏二者兼用!對象