如何在托管的托管Web API .NET上捕获错误并返回该错误...这是我的代码下面的代码....
public static ClientContext GetClientContext(string siteURL, string userName, string password, int foldernam)
{
List<int> folderNames = new List<int>();
folderNames.Add(foldernam);
using (var context = new ClientContext(siteURL))
{
try
{
context.Credentials = new SharePointOnlineCredentials(userName, ToSecureString(password));
Web web = context.Web;
List list = context.Web.Lists.GetByTitle("Bids");
var folder = list.RootFolder;
context.Load(folder);
context.ExecuteQuery();
foreach (int folderName in folderNames)
{
ListItemCreationInformation newItemInfo = new ListItemCreationInformation();
newItemInfo.UnderlyingObjectType = FileSystemObjectType.Folder;
newItemInfo.LeafName = folderName.ToString();
ListItem newListItem = list.AddItem(newItemInfo);
newListItem["Title"] = folderName;
newListItem.Update();
}
context.ExecuteQuery();
return context;
}
catch (Exception ex)
{
// i need to return an error here??????how do i return
//return ClientContext
//throw ex;
}
}
}
使用WebApi2您可以投掷httpresponseexception:
throw new HttpResponseException(HttpStatusCode.NotFound);
看文档。我希望这会有所帮助吗?
编辑:自定义错误信息:从文档中:
要获得对响应的更多控制,您还可以构造整个响应消息,并将其与httpresponseexception一起包含:
public Product GetProduct(int id)
{
Product item = repository.Get(id);
if (item == null)
{
var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent(string.Format("No product with ID = {0}", id)),
ReasonPhrase = "Product ID Not Found"
};
throw new HttpResponseException(resp);
}
return item;
}