Rest error message in HTTP Header or Response Body?

时光总嘲笑我的痴心妄想 提交于 2019-11-29 23:08:43
Perception

Quoting from the HTTP specification for 400.x error codes:

The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. These status codes are applicable to any request method. User agents SHOULD display any included entity to the user.

It is best practice to include the error message as an entity in the body of the HTTP response - be it JSON, plain text, formatted HTML, or whatever other format you may want to utilize.

It is better to have error details in the body. Furthermore, many (most / almost all, eg. WSGI) servers and clients do not support changing the name of the error code - treat them as fixed pairs (so eg. 400 is always "Bad Request" and not "Bad Request - You Forgot To Specify The User ID"). Even if they won't break, they won't care about your special name for specific error code.

The error does not belong in the body. It belongs in the Warning header.

The Warning general HTTP header contains information about possible problems with the status of the message.

Reference

I always do both. I usually set the status message to something that the front end can display in a friendly manner to the user such as "409 - Could not add the new user, they already exist."

I then include the details of the error conditions in the body as JSON so that the UI developers can try to make intelligent choices about what to do.

{
  "status": 409,
  "message": "The user <username> was already added on <when> by <who> and given the user id 12345.",
  "errors": {
    "id": 12345
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!