网站Logo 莉莉安的小站

🔍 Halo UC API 发文章 500 错误排查实录

lilian
1
2026-06-07

背景

莉莉安的博客(lilian.fnidore.top)跑在 Android 手机上,通过 Halo 2.x 搭建。为了能让 AI 助手(曼波 / 诗歌剧)自动发文章,我们使用了 Halo 的个人访问令牌(PAT)来调用 User Center API。

然而,调用 POST /apis/uc.api.content.halo.run/v1alpha1/posts 创建草稿时,始终返回 500 Internal Server Error。而 GET /posts 和 PUT /posts/{name}/publish 却正常工作。

这个 500 错误从 Halo 2.21.0 到 2.24.2 一致存在,看起来像是个陈年 bug。

排查过程

第一回合:以为是权限/CSRF 问题

首先怀疑 PAT 权限不够,但 GET 能用说明认证没问题。尝试加上 X-Requested-With: XMLHttpRequest 头绕过 CSRF——无效。

第二回合:翻源码找到真正原因

查 Halo 服务端日志,发现错误是:

NullPointerException: Post.getMetadata() is null
at UcPostEndpoint.getContent(UcPostEndpoint.java:304)

顺着堆栈翻 UcPostEndpoint.java 源码:

private Mono<ServerResponse> createMyPost(ServerRequest request) {
    var postFromRequest = request.bodyToMono(Post.class)  // 直接把 body 反序列化为 Post
        ...
        .map(post -> new PostRequest(post, ContentUpdateParam.from(getContent(post))))
        .flatMap(postService::draftPost);
}

private Content getContent(Post post) {
    var annotations = post.getMetadata().getAnnotations();  // ← 这里 NPE
    if (annotations != null && annotations.containsKey(CONTENT_JSON_ANNO)) {
        var contentJson = annotations.remove(CONTENT_JSON_ANNO);
        content = JsonUtils.jsonToObject(contentJson, Content.class);
    }
    return content;
}

关键发现

  1. body 直接就是 Post 对象——不需要 {"post":{...},"content":{...}} 的包装。
  2. 内容嵌在 metadata.annotations 里——annotation key 是 content.halo.run/content-json,value 是一个 Content 对象的 JSON 字符串。
  3. metadata.generateName 必填——name 为空时必须提供 generateName(如 "post-")。
  4. spec 有隐藏必填字段——deleted、pinned、priority、publish 缺一不可。

最终能用的请求格式

POST /apis/uc.api.content.halo.run/v1alpha1/posts
Authorization: Bearer <PAT>

{
  "spec": {
    "title": "标题",
    "slug": "url-slug",
    "visible": "PUBLIC",
    "allowComment": true,
    "deleted": false,
    "pinned": false,
    "priority": 0,
    "publish": false,
    "excerpt": {"autoGenerate": true}
  },
  "metadata": {
    "generateName": "post-",
    "annotations": {
      "content.halo.run/content-json": "{\"raw\":\"<p>内容</p>\",\"content\":\"<p>内容</p>\",\"rawType\":\"HTML\",\"version\":1}"
    }
  },
  "apiVersion": "content.halo.run/v1alpha1",
  "kind": "Post"
}

结论

这不是 Halo 的 bug。

Halo 遵循 Kubernetes 资源模型——Post 是一个完整的资源对象(spec + metadata + kind + apiVersion + status),必须按完整结构提交。API 的行为完全符合源码逻辑。

但 Halo 可以改进两点:

  • 异常处理:metadata 为 null 时应返回 400 + 明确提示,而不是裸 NPE → 500。这让排查走了很多弯路。
  • 文档:UC API 的请求格式在官方文档中没有详细说明。content 放在 annotations 里的设计很巧妙,但需要翻源码才能知道。

现在曼波已经能通过 PAT 完整地创建 + 发布文章了——不用浏览器、不用两步验证!🎉

动物装饰