HTTP响应Mojolicious的REST调用中的错误 [英] HTTP reponse for error in REST call for Mojolicious

查看:45
本文介绍了HTTP响应Mojolicious的REST调用中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的Mojolicious应用程序基于JSON,也就是说,客户端与服务器之间的交互更多是JSON结构化数据的交换.

The mojolicious application that I use is JSON based, that is the interaction between the client and the server is more of an exchange of JSON structured data.

当一个REST调用中发生错误时,我正在尝试实现一种使用正确的HTTP响应代码处理错误的标准方法.实施这种标准的最佳方法是什么,该在哪里做?

I am trying to implement a standard way of handling errors with proper HTTP response code when an error occurs during one of the REST calls. What is the best way of implementing such a standard and where do I do it?

我看到了几种实现方法

  1. 创建一个类并列出所有错误响应及其关联的内容,可以使用响应代码对该类进行调用,这将返回包含所有关联内容的JSON结构(哈希和数组的组合)条目,然后在控制器中使用render_json()方法并将其作为对客户端的响应

  1. Create a class and list all the error response and its associated content, a call could be made to this class with the response code, which would return the JSON structure(combination of hashes and arrays) containing all the associated entry, then use the render_json() method in controller and return this as a response to the client

我可以在数据库中创建一个表,其中包含响应所需的所有字段的条目,使用该文件访问JSON结构,创建适当的响应,并在控制器中使用render_json()并将其返回为对客户的回应.

I can create a table in the Database with entry for all the fields that are required for the response, use the filed to access the JSONstructure, create the appropriate response and use render_json() in controller and return this as a response to the client.

错误响应的示例可能像

{
    "Message": "The requested resource is not found"
    "Type" : "http://this.is.an.error.com/error/resource_not_found",
    "ErrorCode" : 404,
    "Created" : "2012-11-05T11:59:29-05:00",
    "Request" : "GET /types/Foo/instances" 
}

标准化这种回应的正确方法是什么?

What is the right way of standardizing such a response?

推荐答案

正如提法中提到的那样,我会选择选项2.

As titanofold mentioned, I'd go for option 2.

关于错误代码,请尝试使用标准的 HTTP响应状态代码. 除了在JSON中设置ErrorCode属性外,您还应该在响应标头中发送状态代码,因为:

Regarding error codes, try to stick with standard HTTP Response Status Codes. Besides setting the ErrorCode property in your JSON, you should send the status code in the response header because:

  • 您可以在一个地方处理错误-javascript函数的error回调
  • 将来您可能还会有其他后端用户(例如移动应用)
  • 这就是为什么他们被发明的原因
  • you can treat errors in a single place - the error callback of your javascript function
  • in the future you might have other consumers of your backend (mobile apps for example)
  • this is why they have been invented

您可以使用Mojolicious做到这一点极其简单:

You can achieve that extremely simple with Mojolicious:

$self->render_json( { 
    Message   => "The requested resource is not found", 
    Type      => "http://this.is.an.error.com/error/resource_not_found", 
    ErrorCode => 404, 
    Created   => "2012-11-05T11:59:29-05:00", 
    Request   => "GET /types/Foo/instances",
   }, 
  status => 404);

这篇关于HTTP响应Mojolicious的REST调用中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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