用 @ExceptionHandler註解實現異常統一處理:java
public class BaseController { private static final Logger logger = LoggerFactory.getLogger(BaseController.class); @ExceptionHandler(Exception.class) @ResponseBody protected ResponseVo handleException(Exception e) { logger.error(e.getMessage(), e); if (e instanceof HttpMessageNotReadableException || e instanceof NumberFormatException || e instanceof InvalidPropertyException){ return new ResponseVo(ResponseStatus.DATA_PARSE_ERROR.VALUE, e.getLocalizedMessage()); } else if (e instanceof NoticeException) { return new ResponseVo(ResponseStatus.FORBIDDEN.VALUE, e.getMessage()); } return new ResponseVo(ResponseStatus.ERROR.VALUE,e.getLocalizedMessage()); } }
若是程序異常會被捕獲,接下來響應的數據就能夠本身定義了
code