While working with custom content query webparts, I have faced some unexpected errors while adding or modifying the webpart through code. After exploring some blogs I found that webpart modification required http context information to implement any modification. So before we fetch the page webpart manager, we must define the context information using the below code:
if (HttpContext.Current == null)
HttpRequest request = new HttpRequest("", web.Url, "");
HttpContext.Current = new HttpContext(request,
new HttpResponse(new StringWriter()));
HttpContext.Current.Items["HttpHandlerSPWeb"] = web;
var manager = web.GetLimitedWebPartManager("default.aspx", PersonalizationScope.Shared);
var contentQuery = new CustomContentQueryWebpart
Title = "My Webpart",
ChromeType = PartChromeType.None
manager.AddWebPart(contentQuery, "Left", 1);
Using the above convention you can avoid most of the unexpected errors related to content query webpart.
Happy SharePointing :)..