如果问题仅仅在于“我如何定义我的错误并准确地告知用户”,我认真介绍一下 RFC7807 所定义的一种媒体格式:application/problem+json
https://tools.ietf.org/html/rfc7807 {
"type": "
https://example.com/probs/out-of-credit",
"title": "You do not have enough credit.",
"detail": "Your current balance is 30, but that costs 50.",
'status": 403,
"instance": "/account/12345/msgs/abc",
"balance": 30,
"accounts": ["/account/12345",
"/account/67890"]
}
其中 type, title, detail, status 和 instance 都是这个规范定义的成员字段,但也都是可选的,此外别的字段都是可以随意拓展的。
其中 status 的存在就可以有效避免楼里说的 HTTP status 被篡改的问题。
type 要求是一个指向人类可读的错误文档的 URI,如果可以确保这个 URI 不变,调用方可以对这个 URI 进行判断来确定错误。title 和 detail 则是提供了人类可读的说明。
这个格式已经有很多语言的实现,Github 上一搜都能出来很多。而且这个格式是 RESTful 的,因为用到了超媒体。
如果传输过程中 HTTP Body 也不幸被修改了,可能会出现的情况是 HTTP Header 的 Content-Type 也被修改,不是 application/problem+json,那么可以确定问题发生在传输过程中。如果 Content-Type 是 application/problem+json 而 body 无法按照这个格式解析,也很容易确定问题发生在传输过程中。
不懂超媒体的就不要再黑 RESTful 了。