失败/错误时 JSON 服务应该返回什么 [英] What should a JSON service return on failure / error

查看:19
本文介绍了失败/错误时 JSON 服务应该返回什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 C#(.ashx 文件)编写一个 JSON 服务.在成功请求服务时,我返回一些 JSON 数据.如果请求失败,要么是因为抛出了异常(例如数据库超时),要么是因为请求在某些方面是错误的(例如,将数据库中不存在的 ID 作为参数提供)服务应该如何响应?哪些 HTTP 状态代码是合理的,我是否应该返回任何数据(如果有)?

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 (e.g. database timeout) or because the request was wrong in some way (e.g. an ID that doesn't exist in the database was given as an argument) how should the service respond? What HTTP status codes are sensible, and should I return any data, if any?

我预计服务将主要使用 jQuery.form 插件从 jQuery 调用,jQuery 或此插件是否有任何默认方式来处理错误响应?

I'm anticipating that service will mainly be called from jQuery using the jQuery.form plugin, does jQuery or this plugin have any default way of handling an error response?

我决定使用 jQuery + .ashx + HTTP [状态代码] 成功时我将返回 JSON 但错误时我将返回一个字符串,正如它所显示的那样这就是 jQuery.ajax 的错误选项所期望的.

I've decided I'll use jQuery + .ashx + HTTP [status codes] on success I'll return JSON but on error I'll return a string, as it appears that that is what the error option for jQuery.ajax expects.

推荐答案

您返回的 HTTP 状态代码应取决于发生的错误类型.如果数据库中不存在 ID,则返回 404;如果用户没有足够的权限进行 Ajax 调用,则返回 403;如果数据库在能够找到记录之前超时,则返回 500(服务器错误).

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 会自动检测此类错误代码,并运行您在 Ajax 调用中定义的回调函数.文档:http://api.jquery.com/jQuery.ajax/

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/

$.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
  }
});

这篇关于失败/错误时 JSON 服务应该返回什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆