PHP:我们可以在Try块

时间:2015-06-03 14:00:34

标签: php

在某些情况下,如果查询失败或者例如=== 1,我都不在意,在这两种情况下我想要return FALSE or die() etc...,所以我会做以下事情:

function test($db){
  try
  {
     $stmt = $db->query("SELECT * FROM table WHERE id=1")->fetch(PDO::FETCH_ASSOC);

     // If Query fails, PDO itself will throw exception,
     // but i also check the value here and throw exception if it's not !== 1

     if ($stmt['column'] === 1)
     {
        throw new PDOException('Wrong Column Info');
     }
     else
     {
        return TRUE;
     }
  }
  catch(PDOException $e)
  {
     return FALSE;
  }
}

我的问题是,我可以使用throw new PDOException,还是应该使用Exception而不是PDOException,然后才能捕获例外?

2 个答案:

答案 0 :(得分:2)

这可以通过很多方式回答。你的方式有效,但可以更明确一点。

这是我的看法:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class ActionPermissionAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        // Override OnAuthorization, not AuthorizeCore as AuthorizeCore will force user login prompt rather than inform the user of the issue.
        var controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
        var action = filterContext.ActionDescriptor.ActionName;

        bool authorised = ... // Check permissions here
        if (!authorised)
            throw new UnauthorizedAccessException("You are not authorised to perform this action.");

        base.OnAuthorization(filterContext);
    }
}

答案 1 :(得分:1)

是的,你可以。尝试使用此代码应该告诉你。

但是,你并不需要。这将完成同样的事情。无论哪种方式都很好,我只是指出了这一点。

function test($db){
  try
  {
     $stmt = $db->query("SELECT * FROM table WHERE id=1")->fetch(PDO::FETCH_ASSOC);

     // If Query fails, PDO itself will throw exception,
     // but i also check the value here and throw exception if it's not !== 1

     if ($stmt['column'] === 1)
     {
        throw new PDOException('Wrong Column Info');
     }
  }
  catch(PDOException $e)
  {
     return FALSE;
  }
  return TRUE;
}