What should a JSON service return on failure / error

后端 未结 11 1111
温柔的废话
温柔的废话 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:27

    The HTTP status code you return should depend on the type of error that has occurred. If an ID doesn't exist in the database, return a 404; if a user doesn't have enough privileges to make that Ajax call, return a 403; if the database times out before being able to find the record, return a 500 (server error).

    jQuery automatically detects such error codes, and runs the callback function that you define in your Ajax call. Documentation: http://api.jquery.com/jQuery.ajax/

    Short example of a $.ajax error callback:

    $.ajax({
      type: 'POST',
      url: '/some/resource',
      success: function(data, textStatus) {
        // Handle success
      },
      error: function(xhr, textStatus, errorThrown) {
        // Handle error
      }
    });
    

提交回复
热议问题