is there a way to customize the HTTP error message in cakePHP exceptions (not in the view but the one shown in Firebug and in ajax response)?
Example: if I call an URL with jQuery ajax function i get this error:
"NetworkError: 400 Bad Request - http://test.localhost/test/add"
because in controller i have
if($duplicated){
throw new BadRequestException("Duplicated element!");
}
I want to change "Bad Request" to "Duplicated element!" and have something like:
"NetworkError: 400 Duplicated element - http://test.localhost/test/add"
and (if possible) return an empty layout if the request is ajax.
My code changes only the text in the standard error view.
thanks in advance!
CakeResponse::httpCodes($code) might help you. But I don't think you can override any existing error codes.
You might consider then creating your own exception.
Related
I want to add exception when a user enters an invalid URL to call the endpoint in Anypoint studio.
Like my default path for calling the API is http://localhost:1234/api/flights, so I want a custom message "Something went wrong!" with a status code of 500 to be shown in an exception when a user enters bad path like http://localhost:1234/24api/flights. I have used APIKit router in this case. Please help me.
Because that is an invalid URI the HTTP Listener and APIKit should be returning a 404 (Not found) status code by default, which is the correct one for this scenario. Returning a 500 status code would be misleading.
I've got a symfony2 bundle where I use jquery terminal project. It's a simple javascript console where the user passes some instructions which are executed on server side with AJAX/JSON and returned to the console and displayed. The php server scripts reads the browser-terminal request from $GLOBALS['HTTP_RAW_POST_DATA'].
Currently, when any request throws an error, symfony2 returns a whole HTML response. I don't want the HTML part (I'd like to display the exception message/code only).
The problem is: symfony2 handles exceptions and catches them somewhere, embedding in HTML and returns such response. I want to modify this - the exc. may be caught, but I want no HTML included. There is one distinct bundle, made only for the console stuff.
In fact, the problem was that there was exit statement missing in the controller. The controller response was empty, so an exception was thrown, that a controller has to return a response. After adding exit; after echoing the output, the problem was gone.
Out of curiosity, are there any popular standards for returning server side exceptions (and corresponding details) in an API that returns JSON? The exceptions could be anything from uncaught exceptions in the code or thrown exceptions put in place by the developer.
Currently I'm setting the HTTP Status Code according to their Wiki definitions'
My JSON response would look something like this:
HTTP Code: 401
{'error': 'Authentication required.', 'message': 'You must be authenticated to perform that action.'}
You can take a look at JSON-RPC (http://en.wikipedia.org/wiki/JSON-RPC).
In case of success, the response is like this:
{
"result": ...(returned data)...
...
}
and in case of error, the response is like that:
{
"error": ...(error details)...
...
}
When the error occured, "error" property must be present and "result" property must not be returned. In case there was no error, "error" property must not be set. This way you can distinguish errors from successful responses based solely on the content of the response, without the need to check the headers (like response codes).
The standard structure of native ECMAScript error objects is:
{
name: ...,
message: ...
}
where "name" is the type of the error (the name of the corresponding constructor, like "Error", "SyntaxError", etc.). In your example, you could use the name "AuthentificationError", for instance.
Yes you can do the same.
As we know that Web servers allow us to create custom error pages for HTTP errors, in those custom error pages you have to serve the JSON reply
Example:
Add the following to your WEB-INF/web.xml:
<error-page>
<error-code>401</error-code>
<location>/autherror.jsp</location>
</error-page>
In the autherror.jsp file code the required logic to accomplish your needed JSON reply.
Try being a bit more verbose regarding the error you are sending. This structure has been suggested in some places to give sufficient information both for users and developer using your API
"error":{
"code":"410",
"long":"410001",
"message":"cannot connect to DB",
"developer":"Connection to the DB was unsuccessful due to ...",
"documentation": "mysite.com/help/errors/..."
}
Return the correct HTTP code for error. It is bad practice to return code 200 with error.
Extend the code with your own error IDs
Provide short message that roughly outlines the cause of the error. Consider adding more detailed message for the developers. Have in mind that API error messages are 99.9% of the time read by developers so make them happy by providing technical details (within reason) so that they can resolve ASAP.
In case you keep public documentation about your api and error codes, simply add the url.
Not a great title but I'm looking more for some guidance, have searched quite a bit. I'm building a web app with an MVC framework (but I think this is a more generic question). I'm trying to make many views that do a lot of AJAX style calls and say I have a site with users and they can add folders and files to their profile page. So the URL maybe like:
/profile/{id}
I have a Profile controller that returns a view with various information. I'd like files and folders listed on the profile to be dynamic so I want to populate it through AJAX calls. I was thinking I would have a URL like
/listFolders/{userId}
and
/listFiles/{folderId}
Is it reasonable to have these URLs return a JSON object for these two URLs and not even provide an HTML view (since, for the browser, the view will just be the whole profile page)? Also, what should I return for errors, say if the user/folder doesn't exist or the current logged in user doesn't have access the data? Is it reasonable to just set 404 or 403 HTTP error codes or do they need to return some kind of HTML? What if there are multiple reasons for it to fail and I'd like to pass that along? Should I arbitrarily choose HTTP error codes or define integer return codes like 0, 1, 2, etc? Also, should the URL specify that they are JSON, like listFoldersJSON instead of listFolders?
I have used JSON in my previous projects. For errors, we return error codes.
We decided to do so because we were dealing with API clients. So we want to deal with error codes (REST is based on HTTP, so it was appropriate to return error codes).
Since you are writing your own application, you can pretty much choose how you want to send your errors to the view. You can create a error json object and in the view you have to check whether this object is not null.
pretty much a if-else in the view. Else you can return error codes and check for the code before rendering the JSON into whatever view you want to.
I would go with error codes, because that complies with the REST philosophy.
Generally speaking, I handle this situation by throwing a 500 internal server error with a status message. Most client libraries such as jQuery provide built in error handling with a failure callback like:
jQuery.ajax({
success:function(response){
//do some success stuff
},
error:function (xhr, ajaxOptions, thrownError){
//handle error
alert(xhr.responseText);
}
});
It's entirely feasible to return JSON objects as opposed to actual views.
As far as the url, you can use listFolders and listFiles without taking on the JSON. However, I recommend you use lower case urls for the sake of how the server is setup. For instance, I know on Apache that sometimes listFiles would be fine, but listfiles would lead to missing page exception.
With regards to errors: You could setup a header of sorts in your JSON response and use whatever system you'd like. For instance, you could do something like
status_code: 0 //where 0 means successful
status_detail:success!
Where, if the status_code is something other than 0, you'd check the status_detail and know to ignore everything else inside the response.
Also, what should I return for errors, say if the user/folder doesn't exist or the current logged in user doesn't have access the data?
These are basic HTTP Error codes:
401 : Unauthorized
404 : Not found
There's a whole slew of error messages in the HTTP spec:
HTTP Status Code Definitions
Also, should the URL specify that they are JSON, like listFoldersJSON instead of listFolders?
Generally, a good way to handle this is for the client to set the 'accepts' header to something like 'text/json' or 'text/xml' and for the server to parse it out and respond with the correct response. This way you can use the same URL but send back different views of the data (if you ever wanted)
I'm trying to standardize the way I handle exceptions in my web application (homemade framework) but I'm not certain of the "correct" way to handle various situations. I'm wondering if there is a best practice from UI/ user-friendly point of view.
User logs into application and opens two tabs showing the same screen. On one tab they issue a delete command on object FOO. Then, in the other tab they then click the edit command on FOO (which no longer exists); e.g. a GET request for editObject.php?object_id=FOO. What should I do when they issue the edit request for this nonexistent object?
-Currently I am redirecting these "missing" objects to the previous page with an error message like "object does not exist".
User issues a GET request to search for Objects with color=Red, e.g. searchObjects.php?color=Red. The query returning these results blew up because somebody dropped the OBJECTS table. This is an unexpected exception and isn't quite the same as 1).
-Currently I am redirecting to errorPage.php with a message "Unexpected error"
In general, what should I do if GET/POST parameters that should be there are instead mysteriously missing. Perhaps somebody is trying to inject something?
-Currently I am treating these the same as 2)
What should I be doing in each of the above 3 cases?
Render a "Object does not exist" view at the url editObject.php?object_id=FOO
Redirect to a controller that displays an error view: header('Location: errorPage.php')
Serve a 404: not sure of the syntax for doing this in PHP/Apache
Other
I'd say render it and serve a 404. That way, the user has the chance to see where they went wrong in the URL, or copy & paste it. If you redirect to a generic error page, they don't have that chance.
The PHP way to serve a 404 is
header("HTTP/1.0 404 not found");