在開發rest接口時,咱們每每會定義統一的返回格式,列如:java
{ "status": true, "code": 200, "message": null, "data": [ { "id": "101", "name": "jack" }, { "id": "102", "name": "jason" } ] }
可是若是調用方請求咱們的api時把接口地址寫錯了,就會獲得一個404錯誤,在傳統的web系統中咱們可自定義404錯誤頁面,展現更友好。web
在spring boot中其實也是返回了一個json格式的數據,以下:spring
{ "timestamp": 1492063521109, "status": 404, "error": "Not Found", "message": "No message available", "path": "/rest11/auth" }
告訴咱們哪一個地址是沒找到,其實也挺友好的,可是由於咱們上面自定義的數據格式跟下面的不一致,當用戶拿到這個返回的時候是沒法識別的,其中最明顯的是status字段。json
咱們自定義的是boolean類型,表示是否成功api
這邊返回的就是http的狀態碼mvc
因此咱們須要在發生這種系統錯誤時也能返回咱們自定義的那種格式app
定義一個異常處理類rest
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; 官網 :www.1b23.com @ControllerAdvice public class GlobalExceptionHandler { private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); /** * 系統異常處理,好比: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是咱們返回格式的實體類code
這種在發生錯誤時這邊會捕獲到,而後封裝好返回格式,返回給調用方接口
最後關鍵的一步是在spring boot的配置文件中加上以下配置:
#出現錯誤時, 直接拋出異常 spring.mvc.throw-exception-if-no-handler-found=true #不要爲咱們工程中的資源文件創建映射 spring.resources.add-mappings=false
而後咱們調用一個不存在的接口時,返回的錯誤信息就是咱們自定義的那種格式了
{ "status": false, "code": 404, "message": "No handler found for GET /rest11/auth", "data": null }