在 Controller 类的逻辑办法中进行失常的响应数据封装, 例如:
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;
}
}
在全局异样解决对象中进行异样响应数据的封装,例如:
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);// 封装异样后果
}
}