What should a JSON service return on failure / error

后端 未结 11 1142
温柔的废话
温柔的废话 2020-12-02 05:32

I\'m writing a JSON service in C# (.ashx file). On a successful request to the service I return some JSON data. If the request fails, either because an exception was thrown

11条回答
  •  臣服心动
    2020-12-02 06:18

    For server/protocol errors I would try to be as REST/HTTP as possible (Compare this with you typing in URL's in your browser):

    • a non existing item is called (/persons/{non-existing-id-here}). Return a 404.
    • an unexpected error on the server (code bug) occured. Return a 500.
    • the client user is not authorised to get the resource. Return a 401.

    For domain/business logic specific errors I would say the protocol is used in the right way and there's no server internal error, so respond with an error JSON/XML object or whatever you prefer to describe your data with (Compare this with you filling in forms on a website):

    • a user wants to change its account name but the user did not yet verify its account by clicking a link in an email which was sent to the user. Return {"error":"Account not verified"} or whatever.
    • a user wants to order a book, but the book was sold (state changed in DB) and can't be ordered anymore. Return {"error":"Book already sold"}.

提交回复
热议问题