精益编程框架

开发文档
点击登录,精彩内容等着你
-

业务异常BLException与页面请求异常PageViewException


关联类名: BLException.java

根据业务统一定义异常,对于简化异常处理,异常抛出,有着重要的作用:

  • 简化因为业务判断,业务主动抛出而强行中断继续运行程序,有利于代码逻辑清晰
  • 统一了异常,有利于对异常进行统一捕捉,把业务错误提示统一反馈到前端

一、业务异常BLException

关键字:BLException,统一定义异常
关联类:com.leanboot.vcore.exception.BLException.java

1.继承RuntimeException

继承运行时异常RuntimeException,确保程序运行有效中断,并有效让数据库操作的service层的事务回滚。

  1. //涉及核心代码
  2. //错误码:有利于指定不同的错误码,前端做出不一样的错误判断
  3. private String code;
  4. //重定向:该参数根据实际业务,页面是否需要重定向到别的页面
  5. private String redirect;

redirect应用说明:
例如是登录超时了,页面通过js请求,发现该code=”session.invalid”,那么需要页面跳转到登录页面,redirect的值就为登录页面地址,(该地址在服务端是通过配置出来的,有利于适应不同的部署环境与绑定域名不同)

2.统一捕捉并处理

对于BLException的统一捕捉,相应的实现在MVC增强组件中,具体在controller成的抽象类BaseController.java中

类路径:com.leanboot.vcore.mvc.controller.BaseController.java

核心代码:

  1. /**
  2. * 13.1统一处理action中各方法抛出的异常
  3. * ajax接口访问主动抛异常
  4. * 手动抛出BLException处理方式
  5. */
  6. @ResponseBody
  7. @ExceptionHandler(BLException.class)
  8. public JSONResult<?> handleBLException(BLException e) throws Exception {
  9. String error = e.getMessage();
  10. String code = ((BLException)e).getCode();
  11. String redirect = ((BLException)e).getRedirect();
  12. return JSONResult.fail(code,error,redirect);
  13. }

注意说明:统一捕捉是在控制层Controller层,这里特意捕捉的BLException,是到达了该层,才会捕捉到;
并且返回是直接json错误返回,所以使用到@ResponseBody这个注解

二、页面异常PageViewException

关键字:PageViewException,统一定义页面展示异常
关联类:com.leanboot.vcore.exception.PageViewException.java

1.继承RuntimeException

继承运行时异常RuntimeException,确保程序运行有效中断,并有效让数据库操作的service层的事务回滚。

  1. //涉及核心代码
  2. // 跳转链接
  3. private String backUrl;
  4. // 错误码
  5. private String code;
  6. // 展示页面,默认error/500.htm,页面也是spring boot 默认的500显示视图
  7. private String page = "error/500";

2.统一捕捉并处理

统一捕捉的实现,跟BLException在同一个地方,涉及到核心代码如下:

  1. //13.2 返回为视图名称路径(一般用于页面手工弹出breakPages())
  2. @ExceptionHandler(PageViewException.class)
  3. public String handleException(HttpServletRequest request, PageViewException e) throws Exception {
  4. System.out.println("-----PageViewException-----");
  5. request.setAttribute("error", e.getMessage());
  6. request.setAttribute("code", e.getCode());
  7. request.setAttribute("backUrl", e.getBackUrl());
  8. request.setAttribute("now", DateUtil.formatDate(new Date()));
  9. return e.getPage();//默认/error/500.html
  10. }

三、总结

精益编程Leanboot对代码的每一个细节都细心雕琢,力求达到精炼易懂。
关于统一捕捉异常的功能点,涉及到多个知识点,后续将完善这一部分的功能说明。