您好,登錄后才能下訂單哦!
在開發(fā)rest接口時(shí),我們往往會(huì)定義統(tǒng)一的返回格式,列如:
{??"status":?true,??"code":?200,??"message":?null,??"data":?[ ????{??????"id":?"101",??????"name":?"jack" ????}, ????{??????"id":?"102",??????"name":?"jason" ????} ??] }
但是如果調(diào)用方請(qǐng)求我們的api時(shí)把接口地址寫錯(cuò)了,就會(huì)得到一個(gè)404錯(cuò)誤,在傳統(tǒng)的web系統(tǒng)中我們可自定義404錯(cuò)誤頁(yè)面,展示更友好。
在spring boot中其實(shí)也是返回了一個(gè)json格式的數(shù)據(jù),如下:
{??"timestamp":?1492063521109,??"status":?404,??"error":?"Not?Found",??"message":?"No?message?available",??"path":?"/rest11/auth"}
告訴我們哪個(gè)地址是沒找到,其實(shí)也挺友好的,但是因?yàn)槲覀兩厦孀远x的數(shù)據(jù)格式跟下面的不一致,當(dāng)用戶拿到這個(gè)返回的時(shí)候是無法識(shí)別的,其中最明顯的是status字段。
我們自定義的是boolean類型,表示是否成功
這邊返回的就是http的狀態(tài)碼
所以我們需要在發(fā)生這種系統(tǒng)錯(cuò)誤時(shí)也能返回我們自定義的那種格式
定義一個(gè)異常處理類
import?javax.servlet.http.HttpServletRequest;import?javax.servlet.http.HttpServletResponse;import?org.slf4j.Logger;import?org.slf4j.LoggerFactory;import?org.springframework.web.bind.annotation.ControllerAdvice;import?org.springframework.web.bind.annotation.ExceptionHandler;import?org.springframework.web.bind.annotation.ResponseBody; 官網(wǎng)?:www.1b23.com? @ControllerAdvicepublic?class?GlobalExceptionHandler?{????private?Logger?logger?=?LoggerFactory.getLogger(GlobalExceptionHandler.class);? ????/** ?????*?系統(tǒng)異常處理,比如:404,500 ?????*?@param?req ?????*?@param?resp ?????*?@param?e ?????*?@return ?????*?@throws?Exception ?????*/ ????@ExceptionHandler(value?=?Exception.class)????@ResponseBody ????public?ResponseData?defaultErrorHandler(HttpServletRequest?req,?Exception?e)?throws?Exception?{ ????????logger.error("",?e); ????????ResponseData?r?=?new?ResponseData(); ????????r.setMessage(e.getMessage());????????if?(e?instanceof?org.springframework.web.servlet.NoHandlerFoundException)?{ ?????????????r.setCode(404); ????????}?else?{ ?????????????r.setCode(500); ????????} ????????r.setData(null); ????????r.setStatus(false);????????return?r; ????} }
ResponseData是我們返回格式的實(shí)體類
這種在發(fā)生錯(cuò)誤時(shí)這邊會(huì)捕獲到,然后封裝好返回格式,返回給調(diào)用方
最后關(guān)鍵的一步是在spring boot的配置文件中加上如下配置:
#出現(xiàn)錯(cuò)誤時(shí),?直接拋出異常spring.mvc.throw-exception-if-no-handler-found=true#不要為我們工程中的資源文件建立映射spring.resources.add-mappings=false
然后我們調(diào)用一個(gè)不存在的接口時(shí),返回的錯(cuò)誤信息就是我們自定義的那種格式了
{??"status":?false,??"code":?404,??"message":?"No?handler?found?for?GET?/rest11/auth",??"data":?null}
?
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。