在开发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 }