【问题标题】:Exception Filter Attribute does not catch Exception(Web API 2)异常过滤器属性不捕获异常(Web API 2)
【发布时间】:2017-08-26 00:42:33
【问题描述】:

我是一个新手,正在开发一个简单的 API 项目。当我的 SQL 服务器离线时,我试图在我的控制器中捕获一个异常。

可以看出我正在使用依赖注入。如果我不使用 DI 并仅通过创建上下文来访问数据库,我可以捕获异常。

所以基本上我被卡住了。

控制器:

public class PlayersController : ApiController
{
    IRepositoryBase<Player> players;

    public PlayersController(IRepositoryBase<Player> players)
    {
        this.players = players;
    }

    [ApiException]
    //GET: /api/players
    public IHttpActionResult Get()
    {            
        var playerList = players.GetAll();                
        return Ok(playerList);                         
    }

API 异常过滤器:

public class ApiException : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext actionExecutedContext)
    {
        HttpResponseMessage errorResponse = new HttpResponseMessage(HttpStatusCode.NotImplemented);
        errorResponse.ReasonPhrase = actionExecutedContext.Exception.Message;
        actionExecutedContext.Response = errorResponse;
        base.OnException(actionExecutedContext);
    }
}

【问题讨论】:

  • 您是否尝试过调试,发现它确实没有运行OnException 中的代码?由于我尝试运行您编写的代码(在 Get() 操作中使用简单的 throw new Exception() 来检查)并且它有效。此外,您应该使用属性后缀命名您的属性类,即ApiExceptionAttribute
  • 好吧,当我调试程序时直接通过了过滤器。我已经手动停止了 SQL 服务器,在“var playerList = player.GetAll();”上放了一个断点,运行应用程序并刷新页。但它只是给了我一个 500 内部服务器错误。我的目标是不执行 501。
  • @M.Aroosi 难道是因为我使用了存储库模式?
  • 尝试在OnException 方法中放置断点。另外,尝试单步执行GetAll 方法,看看是否确实抛出了异常。
  • 顺便说一句,您遇到的内部服务器错误是什么(使用浏览器的网络检查器)?

标签: c# asp.net exception-handling


【解决方案1】:

我能够为我的问题提供解决方案。不知道这样是否正确。

我重新设计了我的 RepositoryBase 构造函数,以便在关闭数据库连接时创建一个为空的上下文。

RepositoryBase:

public RepositoryBase(DataContext _context)
    {
       if (_context.Database.Connection.State == ConnectionState.Closed)
       {
            this._context = null;
            this._dbSet = null;
       }
       else
       {
            this._context = _context;
            this._dbSet = _context.Set<TEntity>();
       }

然后我更新了 GetAll() 方法,这样如果它看到一个空上下文就会抛出一个异常。

GetAll():

    public virtual IQueryable<TEntity> GetAll()
    {
        if (_context==null)
        {
            throw new NotImplementedException("DB Not Found");
        }                 
        return _dbSet;
    } 

然后这个异常被 ApiExceptionAttribute 捕获,它确保客户端收到异常代码和我抛出的自定义消息。

【讨论】:

    猜你喜欢
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    • 2022-07-07
    • 2014-10-13
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 2014-05-28
    相关资源
    最近更新 更多