关于404,500等错误处理

问题描述,请详细查看https://www.jfinal.com/feedback/6663

以下是有@jfinal 提供的思路处理的;

@Override
public void configConstant(Constants constants) {
    PropKit.use("undertow.properties");
    MODE = PropKit.get("undertow.config.mode", "debug");
    PropKit.append(StrUtil.format("global_config_{}.properties", MODE));
    IS_DEBUG = "debug".equals(MODE);
    constants.setInjectDependency(true);
    constants.setInjectSuperClass(true);
    constants.setDevMode(true);
    constants.setLogFactory(new Slf4jLogFactory());
    constants.setJsonFactory(new MixedJsonFactory());
    constants.setRenderFactory(new ExceptionRenderFactory());
}

public class ExceptionRenderFactory extends RenderFactory {

    @Override
    public Render getErrorRender(int errorCode) {
        return getErrorRender(errorCode,constants.getErrorView(errorCode));
    }

    @Override
    public Render getErrorRender(int errorCode, String view) {
        LogKit.error(StrUtil.format("ExceptionRenderFactory 错误码处理【errorCode:{},view:{}】", errorCode, view));
        return new ExceptionRender(errorCode,view);
    }
}

public class ExceptionRender extends ErrorRender {

    private static final String jsonOrther = "{\"msg\":\"{}【服务器内部未知错误,请联系平台】\",\"state\":\"fail\"}";
    private static final String json404 = "{\"msg\":\"404【请求资源不存在】\",\"state\":\"fail\"}";

    public ExceptionRender(int errorCode, String view) {
        super(errorCode, view);
        LogKit.error(StrUtil.format("ExceptionRender 错误码处理【errorCode:{},view:{}】", errorCode, view));
    }

    @Override
    public void render() {
        String url = this.request.getServletPath();
        this.response.setStatus(this.getErrorCode());
        if (this.getErrorCode() == 400
                || this.getErrorCode() == 401
                || this.getErrorCode() == 403
                || this.getErrorCode() == 404
                || this.getErrorCode() == 500){
            if (url.startsWith("/api")){
                String errorJson = this.getErrorJson();
                RenderManager.me().getRenderFactory().getJsonRender(errorJson).setContext(this.request, this.response).render();
            }else {
                super.render();
            }
        }else{
            super.render();
        }
    }

    private String getErrorJson() {
        int errorCode = this.getErrorCode();
        if (errorCode == 404) {
            return json404;
        } else {
            return StrUtil.format(jsonOrther,errorCode);
        }
    }

}


评论区

JFinal

2019-10-25 18:59

方案简单,代码简洁,谢谢你的分享

热门分享

扫码入社