package com.ruoyi.framework.filter;

import com.ruoyi.common.constants.HttpConstant;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.exception.StatusException;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.noear.solon.core.handle.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 全局过滤器
 * @author ruoyi
 */
@Component
public class GlobalFilter implements Filter {

    private static final Logger log = LoggerFactory.getLogger(GlobalFilter.class);

    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        handleFilter(ctx, chain);
    }

    /**
     * 捕获全局异常，统计执行耗时
     * @param ctx
     * @param chain
     * @throws Throwable
     */
    private void handleFilter(Context ctx, FilterChain chain) throws Throwable {
        long start = System.currentTimeMillis();
        try {
            chain.doFilter(ctx);
        } catch (StatusException e) {
            // 自带状态码的异常，包含鉴权异常、数据校验异常、自定义业务异常
            ctx.render(Result.failure(e.getCode(), e.getMessage()));
        } catch (Throwable e) {
            // 其它异常
            e.printStackTrace();
            ctx.render(Result.failure(HttpConstant.HTTP_INTERNAL_ERROR, e.getMessage()));
        }
        long times = System.currentTimeMillis() - start;
        log.info("请求【{}】【{}】完成，耗时:【{}ms】", ctx.path(), ctx.method(), times);
    }

}
