当前位置: 动力学知识库 > 问答 > 编程问答 >

rest - Restful API - JSON response with single or all error(s)

问题描述:

My current project, a restful API, validates a POST request to create a new user and multiple errors could occur (with HTTP status):

  1. username not set (400 BadRequest)
  2. username is taken (409 Conflict)
  3. server can't establish db connection (500 Internal Server Error)
  4. ...

Should I immediatly send back a JSON response like this

{

"status": 400,

"Message": "No username is set"

}

if an error was detected or should is it better if I accumulate all errors like here:

{

"status": <HTTP STATUS CODE>,

"errors": [

{"message": "Username is not set."},

{"message": "Can't access the database."}

]

}

The last approach would not require multiple request to send a valid payload. But which status code should be used, if the username is not set (400 Bad Request) or the server can't access the database (500 Internal Server Error)?

网友答案:

I think if you foresee the need for multiple errors in one request, then the second JSON (with the multiple errors) is preferred. Another benefit of doing the multiple errors response is that as a user of your service, if i get back multiple errors, I can address them all at one shot, instead of addressing them one at a time as I get them.

分享给朋友:
您可能感兴趣的文章:
随机阅读: