在Controller類的邏輯方法中進行正常的響應數據封裝,例如:web
package com.cy.pj.module.controller; @RestController public class ArithmeticController { @RequestMapping("/doCompute/{n1}/{n2}") public JsonResult doCompute(@PathVariable Integer n1, @PathVariable Integer n2){ Integer result=n1/n2; JsonResult r=newJsonResult("計算結果:"+result); r.setData(result); return r; } }
在全局異常處理對象中進行異常響應數據的封裝,例如:app
package com.cy.pj.common.web; @RestControllerAdvice public class GlobalExceptionHandler { private static final Logger log=LoggerFactory.getLogger(GlobalExceptionHandler.class); @ExceptionHandler(ArithmeticException.class) public JsonResult doHandleArithmeticException(ArithmeticException e){ e.printStackTrace(); log.info("exception {}",e.getMessage()); return new JsonResult(e);//封裝異常結果 } }