【问题标题】:Exception handling in Web API Controller and throwing custom error messageWeb API 控制器中的异常处理和抛出自定义错误消息
【发布时间】:2017-08-31 12:51:16
【问题描述】:

对于我的一个项目,我正在使用带有 SOA 架构的 Web API。在控制器中,我想捕获异常(由存储库抛出)并返回 HttpResposeMessage

我想要的是应该有一个继承 ApiController (class BaseController : ApiController) 的 BaseController 并且我的每个控制器都应该由 baseController 继承
例如class TaskController : BaseController 如果我的控制器发生任何异常,则应由 BaseController 处理。 演示:

以下是我们的 VS 解决方案中的项目:(项目结构)

XYZ.Model
XYZ.Repository
XYZ.WebServices
XYZ.Exception
XYZ.UI

代码: XYZ.模型

public class Error
{
    public string Code { get; set; }
    public string Message { get; set; }

}

XYZ.异常

// To create the custom exception as per our need
public class BaseException : Exception
{
    private Error _error;
    public Error Error
    {
        get { return _error; }
    }

    public BaseException()
    {
        _error = new Error();
    }

    public void SetErrorCode(string code)
    {
        _error.Code = code;
    }

    public void SetErrorMessage(string message)
    {
        _error.Message = message;
    }
}


public class TaskNotFoundException : BaseException
{
    public TaskNotFoundException()
    {
        string errorCode = "T0001";
        base.SetErrorCode(errorCode);
        base.SetErrorMessage((new ExceptionMessage()).GetExceptionMessage(errorCode));
    }
}

XYZ.Repository

public Task UpdateTaskDetails(Task task)
{
    try
    {
        //--Task updating logic--//
    }
    catch (Exception ex)
    {
        throw new TaskUpdateFailedException();
    }
    return task;
}

XYZ.WebServices

public class BaseController : ApiController
{
    public HttpResponseMessage CreateResponseMessage()
    {
        try
        {
            GetTasksByUserIdAndProjectId(new TaskQuery());
        }
        catch(BaseException exception)
        {
            return Request.CreateResponse(HttpStatusCode.InternalServerError, exception.Error);
        }
    }

    public virtual  List<Task> GetTasksByUserIdAndProjectId(TaskQuery query)
    {
        Console.WriteLine("I can be overridden");
    }
}


public class TaskController : BaseController
{
    [HttpPost]
    public override List<Task> GetTasksByUserIdAndProjectId(TaskQuery query)
    {
        return _taskRepo.GetTasksByUserIdAndProjectId(query.UserId, query.ProjectId);
    }

}

TaskController 中,如果GetTasksByUserIdAndProjectId 方法中发生任何异常,它应该将异常抛出到BaseController CreateReponseMessage(),然后它将HttpResponseMessage 返回给客户端。

注意:在每个控制器中都有多个 Get/Put/Post 方法,因此无法在BaseController 中声明所有方法(Web Service 方法)来捕获我项目当前结构中子类的异常。

有没有更好的方法来处理 Web API 中的异常,以便轻松融入我的项目?

【问题讨论】:

  • 这可以使用异常过滤器更好地完成。
  • @Nkosi,感谢您的建议,我已经实现了异常过滤器并且运行良好。但我还有一个问题“我们可以在异常过滤器中处理一些验证失败错误之类的事情吗?AS 验证失败不是异常,但我希望它在一个公共类中处理。”

标签: c# asp.net-web-api exception-handling soa


【解决方案1】:

我们使用这样的异常过滤器:

首先我们创建自己的异常:

public class UserFriendlyException: Exception
    {
        public UserFriendlyException(string message) : base(message) { }
        public UserFriendlyException(string message, Exception innerException) : base(message, innerException) { }
    }

然后我们创建一个过滤器:

public class UserFriendlyExceptionFilterAttribute: ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext context)
        {
            var friendlyException = context.Exception as UserFriendlyException;
            if (friendlyException != null)
            {
                context.Response = context.Request.CreateResponse(HttpStatusCode.BadRequest, new {Message = friendlyException.Message}); 
            }
        }
    }

最后,我们在 WebApi 的配置中添加该过滤器。

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            ...


            config.Filters.Add(new UserFriendlyExceptionFilterAttribute());

            ...
        }
    }

使用此解决方案,您可以在代码中的任何位置抛出 UserFriendlyException,响应将根据过滤器。

【讨论】:

  • 感谢您的回答,我已经实现了异常过滤器并且工作正常。但我还有一个问题“我们可以在异常过滤器中处理一些验证失败错误吗?AS 验证失败不是异常,但我希望它在一个公共类中处理。”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-18
  • 2017-09-26
  • 2010-09-27
  • 1970-01-01
  • 2019-07-26
相关资源
最近更新 更多