检查结果是否正确 [英] check that a result is an ok playframework

查看:104
本文介绍了检查结果是否正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过使@Cached注释了解我在控制器中调用的函数的参数来做出更好的注释.

I am trying to make a slightly better @Cached annotation by making it aware of the parameters of the function I call in my controllers.

所以我有这个动作:

public class ContextualCachedAction extends Action<ContextualCached> {

    @Override
    public Result call(Context ctx) throws Throwable {
        try {
            String key = makeKey(ctx);
            Integer duration = configuration.duration();
            Result result = (Result) Cache.get(key);
            if (result == null) {
                result = delegate.call(ctx);

                //TODO find a way to cache only successful calls

                Cache.set(key, result, duration);
            }
            return result;
        } catch (RuntimeException e) {
            throw e;
        } catch (Throwable t) {
            throw new RuntimeException(t);
        }
    }

    private String makeKey(Context ctx) {
        //makes the key from some parameters in the ctx.request()
    }
}

我的问题是:仅当它是Ok()时,我才想缓存proxy.call()的结果. 我该如何检查? 有财产吗? 实用程序? 还是我需要Ok().getClass().isInstance(result)?

My question is this : I would like to cache the result of delegate.call() only if it is an Ok(). How can I check for that? Is there a property? a util? or do I need to Ok().getClass().isInstance(result)?

感谢您提供任何答案和提示.

Thanks for any answers and hints.

PS:为什么我要这么做?因为我有一些电话会产生几种类型的不同结果.很少有结果可以选择将其缓存,因为我不想

PS : Why do I want to do that? Because I have some calls that generate few types of different results. Few enough results that caching them could be an option since I don't want to

推荐答案

ok结果实际上是一个play.mvc.Results.Status,它包装了其Scala副本play.api.mvc.Results.Status,后者又将其status代码设置为200.

An ok result is actually a play.mvc.Results.Status which wraps its Scala counterpart play.api.mvc.Results.Status, which in turn has its status code set to 200.

因此,您调用result.getWrappedResult()并检查类型是否正确,将其强制转换为PlainResult(最小公分母),然后调用status.

So you call result.getWrappedResult() and check if the type is right, cast it to PlainResult (the lowest common denominator) and call status.

这看起来很丑:

  play.api.mvc.Result wrappedResult = result.getWrappedResult();
  if (wrappedResult instanceof play.api.mvc.PlainResult) {
    play.api.mvc.PlainResult plainResult = (play.api.mvc.PlainResult)wrappedResult;
    int code = plainResult.header().status();
    if (code == OK)
      // Cache
  }

这篇关于检查结果是否正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆