【问题标题】:Best practice to report error to jQuery from Spring MVC从 Spring MVC 向 jQuery 报告错误的最佳实践
【发布时间】:2013-05-26 23:36:48
【问题描述】:

我的问题与标题中提到的完全一样。我有 Spring webservices 返回 JSON 响应。以下哪项是处理错误的优雅方式:

  1. 从 Spring MVC 控制器抛出一个异常,然后由 jQuery 的错误函数处理。

  2. 发送 JSON 响应设置,例如。 result="failure" 然后在jquery的success函数中查看'result'的值

    我想了解这两种方法的优缺点。

谢谢

【问题讨论】:

  • 在第一个场景中,您究竟想如何使用 jQuery 处理异常?无论如何,execptions 通常运行缓慢,所以尽可能不要抛出它们。
  • 完全像下面提到的@Bhashit,返回HTTP代码

标签: jquery ajax spring-mvc error-handling


【解决方案1】:
function addCustomer(){
      $.post( "customer/addCustomer", addCustomerForm.serialize() )
     .done(function(data) {
         if(data==='OK'){
             alert( "Customer saved");
         }else{
             alert(data);
         }
      }).fail( function(xhr, textStatus, errorThrown) {
         alert(textStatus + ":" + errorThrown);
      });
 }

 @RequestMapping(value = "addCustomer", method = RequestMethod.POST)
public  @ResponseBody String addCustomer(

        @RequestParam(required = true, value="add-customer-name") String customerName,
        @RequestParam(required = true, value="add-customer-city-name") String customerCity,
        @RequestParam(required = true, value="add-customer-distributer") String distributerNodeName,
        @RequestParam(required = true, value="add-customer-accountid") String accountId

    ){

    try{

        customersDao.createCustomer(customerName,customerCity, distributerNodeName, accountId);

    }catch(SQLException e){
        logger.error("create customer failed", e);
        return "error:"+e.getMessage();
    }catch(AlreadyExistsException e){
        logger.error("create customer failed", e);
        return "error:"+e.getMessage();
    }catch(QuoteLimitException e){
        logger.error("create customer failed", e);
        return "error:"+e.getMessage();
    }catch(Exception e){
        logger.error("create customer failed", e);
        return "error:"+e.getMessage();
    }

    return "OK";
}

【讨论】:

    【解决方案2】:

    通过success 或其他类似标志报告请求处理中的错误是开发 Web 服务的标准做法。也就是说,如果您的请求成功,则 JSON 响应中的该标志指示 success,否则指示 failure。您的 JSON 响应中可能还有其他 properties 可以携带适当的消息,如果请求成功,另一个字段可以携带您的结果数据。

    当您以这种方式开发服务时,您的 Web 服务的使用者不再依赖于自定义异常处理。使用您的第一种方法时,他们必须自己解释 HTTP 代码并据此确定行动方案。这总是会导致客户端出现大量错误处理代码(可能在使用服务的任何地方重复)。相反,通过一个简单的错误标志,他们可以检查该标志并确定请求是否成功,并显示适当的消息或采取其他一些措施。

    我参与了一些网络服务(开发和消费)的处理,我从未处理过依赖于 Ajax 调用的 error 处理程序的网络服务.

    第一种方法的优点是您现在可以真正将成功的请求与不成功的请求区分开来。但是,在这种情况下,请确保您自己在服务器端处理这些异常,并根据这些异常返回适当的状态代码。如果您不这样做,大多数异常将导致HTTP 错误代码为500,并且您的Web 服务客户端可能很难以某种通用方式对其进行解释。

    关于在 API 中处理错误的正确方法的小讨论,see here

    【讨论】:

    • 感谢您的详细解释
    猜你喜欢
    • 2020-11-02
    • 1970-01-01
    • 2015-09-11
    • 2010-11-16
    • 1970-01-01
    • 2015-04-19
    • 2011-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多