问题
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.
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?
I see a couple of ways of doing it
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
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.
Example of error response might be like
{ "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?
回答1:
As titanofold mentioned, I'd go for option 2.
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:
- 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
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);
回答2:
The wonderful things about standards are that there are so many to choose from, and if you don't like any of them you can make your own.
As to the REST structure, that's up to you. I would go for the generic 'code' rather than 'ErrorCode' as you should return a code on success, too.
For your method options, I'd go with option 2.
回答3:
I would also opt for option 2. But I do not understand the need for the error details to be part of the database. I would rather suggest you use a the OO concept of base class holding all the error details and the inheriting it to other classes, making sure you have access to it.
来源:https://stackoverflow.com/questions/13239501/http-reponse-for-error-in-rest-call-for-mojolicious