Controller层中使用try catch功能
1 public Wrapper billQuery(@RequestBody OrderBillQueryReq orderBillQueryReq){ 2 log.info("账单列表查询入参:{}", JSON.toJSONString(orderBillQueryReq)); 3 try { 4 PageList<OcOrderBillInfoDto> billList = orderBillService.list(orderBillQueryReq); 5 return WrapMapper.ok(new PageVO<>(billList)); 6 } catch (Exception e) { 7 log.error("查询账单列表失败,错误信息:{}", e.getMessage(),e); 8 return WrapMapper.error(e.getMessage()); 9 } 10 } 11 }
ServiceImpl层中是否使用try catch功能对Controller层的影响
1,使用try catch功能,抓Exception
1 public PageList<OcOrderBillInfoDto> list(OrderBillQueryReq orderBillQueryReq) { 2 try { 3 List<Integer> listIN = new ArrayList<>(); 4 listIN.get(2); 5 } catch (Exception e) { 6 log.error("错误信息:{}", e.getMessage(),e); 7 } 8 9 //业务逻辑 10 return new PageList<>(listModel,pageList.getPaginator()); 11 }
结果:service层会打印错误日志,Controller层不打印错误信息和日志。但是下面的业务代码会继续执行,向前端输出正常结果。
1 [service-xx-bill] 2020-04-08 10:27:27.932 [http-nio-9100-exec-1] ERROR c.w.s.c.bill.service.impl.OrderBillServiceImpl - 错误信息:Index: 2, Size: 0 2 java.lang.IndexOutOfBoundsException: Index: 2, Size: 0 3 at java.util.ArrayList.rangeCheck(ArrayList.java:657) 4 at java.util.ArrayList.get(ArrayList.java:433) 5 at xxxxxxxl.OrderBillServiceImpl.list(OrderBillServiceImpl.java:56) 6 at xxxxxxx.controller.OrderBillController.billQuery(OrderBillController.java:59) 7 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
2,不使用try catch功能。
1 public PageList<OcOrderBillInfoDto> list(OrderBillQueryReq orderBillQueryReq) { 2 List<Integer> listIN = new ArrayList<>(); 3 listIN.get(2); 4 5 //业务逻辑 6 return new PageList<>(listModel,pageList.getPaginator()); 7 }
结果:service层不打印错误日志,Controller层打印错误信息和日志。下面的业务代码不会继续执行,向前端输出错误信息。
1 [xxxx-bill] 2020-04-08 10:38:37.259 [http-nio-9100-exec-2] ERROR c.w.s.c.bill.controller.OrderBillController - 查询账单列表失败,错误信息:Index: 2, Size: 0 2 java.lang.IndexOutOfBoundsException: Index: 2, Size: 0 3 at java.util.ArrayList.rangeCheck(ArrayList.java:657) 4 at java.util.ArrayList.get(ArrayList.java:433) 5 at xxxx.bill.service.impl.OrderBillServiceImpl.list(OrderBillServiceImpl.java:55) 6 at xxxx.bill.controller.OrderBillController.billQuery(OrderBillController.java:59) 7 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)