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

查看:94
本文介绍了失败/错误时,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;否则,返回404.如果用户没有足够的特权进行该Ajax调用,则返回403;否则,返回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天全站免登陆