jfinal-4.9 增加全局异常拦截器
[思路]
编写1个实例类
添加拦截器,拦截异常,封装到实体类中,返回json数据
编辑一个实体类
package com.litong.jfinal.vo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class JsonBean<T> { private int code = 0; // 状态码 private String msg = "执行成功"; // 状态说明 private T data; // 数据内容 public JsonBean(T data) { this.data = data; } public JsonBean(int code) { this.code = code; } public JsonBean(String msg) { this.msg=msg; } public JsonBean(int code, String msg) { this.code = code; this.msg = msg; } }
全局异常拦截器
package com.litong.jfinal.interceptor; import com.jfinal.aop.Interceptor; import com.jfinal.aop.Invocation; import com.jfinal.core.Controller; import com.litong.jfinal.vo.JsonBean; import lombok.extern.slf4j.Slf4j; /** * @author bill robot * @date 2020年8月29日_下午5:45:26 * @version 1.0 * @desc * 全局异常烂机器 */ @Slf4j public class ExceptionInterceptor implements Interceptor { @Override public void intercept(Invocation invocation) { try { // 执行方法 invocation.invoke(); } catch (Exception e) { e.printStackTrace(); log.error(e.getMessage()); Controller c = invocation.getController(); c.renderJson(new JsonBean<Void>(-1,e.getMessage())); } } }
添加拦截器
@Override public void configInterceptor(Interceptors me) { me.addGlobalActionInterceptor(new ExceptionInterceptor()); }