In my API if any query fails then what should be the response status code?
Example :
Grade.find({},function(err,grades) {
if (err)
res.status(500).json({error:err,message: 'Somthing went wrong please try again later'});
else
res.status(200).json({grades:grades});
});
Is 500 OK or should it be something else ?
TL;DR A 500 status is the closest thing to a 'one size fits all' error, but you can get into much deeper details.
According to the standards, you have plenty of choices :
5xx Server Error
500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable
504 Gateway Timeout
510 Not Extended
You could also create your own 5xx status to differentiate between error types, just try to use numbers that are not defined for anything else.
Or stick to a 500 status and attach the original error code to your result :
res.status(500).json({error:err, code : err.code, message: 'Somthing went wrong please try again later'});
However, before answering with 5xx, you want to make sure that the error doesn't come from the client, by validating the data you receive. If the received data is invalid, use a 400 Bad Request code. If the issue is security related, use a 403 Not Authorized, etc...
According to http status codes you can use 5xx for server error and 4xx for client error.
Related
So, i got an apollo server running and an apollo-client in my iOS app.
I'm trying to implement an authentication process. And following apollo's documentation about authorization and authentication, i ended up trying the code they provided :
context: ({ req }) => {
throw new AuthenticationError('you must be logged in');
},
But, while testing the code, i discovered that throwing an error wether it is a javascript one, or an apollo error, it always sends back an http 400 error :
Error: Response not successful: Received status code 400
at new ApolloError (errors.cjs.js:31)
at core.cjs.js:1493
at both (utilities.cjs.js:963)
at utilities.cjs.js:956
at tryCallTwo (core.js:45)
at doResolve (core.js:200)
at new Promise (core.js:66)
at Object.then (utilities.cjs.js:956)
at Object.error (utilities.cjs.js:964)
at notifySubscription (Observable.js:140)
The authentication error is not sent back. Even when i throw a custom error, with custom status code and everything it always returns the same error.
Am i doing something wrong ? Or is this an issue ?
If you do not count on receiving a 401 error code for any downstream tasks, I don't think it is an issue you need to worry about. However, if you do need to receive the expected 401, you can use Apollo Link for error handling. Read about it here: https://www.apollographql.com/docs/react/data/error-handling/#advanced-error-handling-with-apollo-link
If you still cannot fix the problem, browsing through this issue may also be helpful: https://github.com/apollographql/apollo-server/issues/1709
Hope this helps, happy coding :)
I'm calling an API with a JWT. When the token expires or when I send an invalid token, I get a 401 in postman, but when I do it in browser, I get a "Network error". And it works when the token is valid.
I use axios to call the API and the error.response is undefined. When I stringify the error object in catch I see something like this:
{
message : 'Network Error',
name : 'Error',
stack : 'Error: Network Error\n at createError (webpack-internal:///./node_modules/axios/lib/core/createError.js:16:15)\n at XMLHttpRequest.handleError (webpack-internal:///./node_modules/axios/lib/adapters/xhr.js:83:14)'
}
I get 200 in the OPTIONS request, but in the main GET request I get the above error. This is probably because of CORS. But I don't know what to change. The Access-Control-Allow-Origins is *.
I don't understand why I don't get the 401 in browser. Can someone please tell me how to fix this?
Screenshot of network tab:
Options:
Your server is probably not setting Access-Control-Allow-Credentials to true to allow origin access to authorized users.
I don't think you actually have a bug. It's just that axios throws on all 4xx responses by default. Try the following:
axios.get("...", { validateStatus(status) { return true; } })
To fix it up, try add other Cross-Origin Resource Sharing (CORS) headers. Check them at
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
I use redux promise middleware for my front end. so action.type will catch if there any error, but what's the correct status code for error I should throw from my backend?
I know I can do res.status(500).json(something)
but is 500 correct code for error? like invalid password, should I throw 500 too?
You can check out the error code in wiki as well as , they have mention all the error status code you should use.
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
Most if you have error related to the data in the api , password wrong they come under 4XX error.
Like Password error you should give 401 Unauthorized
In my Google Chrome console I keep receiving errors when the xmlhttp status does not result in 200. For example, in certain cases I intentionally set the header of my PHP files to 500 so in javascript I can display the error and avoid anything that requires that PHP file. Since I have my own error handler for this, is there anyway to suppress the default error?
Error Example:
POST http://localhost/mama/cgi-bin/pages/Module-Install.php 500 (Internal server error)
It seems that there is no way to supress these warnings in google chrome when handling the error yourself. For any of those who are looking for an alternate solution, embed the error code in a json object, and parse the json object client side for any errors.
This error was sended by Server side, not browser, not js. You can not just "hide" it from console. You can handle it in onerror event:
request.onerror = function (e) {
// do something to fix the results of server error...
};
In other words, this is a server error and it CAN break your code execution, but if you make couple steps to resume the job after a possible exception from xmlHttp class, the code will be fine.
UPD:
Just if you are pure perfectionist, and you cares about flawless environment:
In a server side you must implement the server answer without a firing any statuses except 200. It's not a super hard job.
For ASP: Suppressing HTTP 500 response codes;
For PHP: http://php.net/manual/en/function.http-response-code.php .
I would like to know what is best practice with AJAX authentication process.
When authentication is valid I return HTTP header 200 with response "ok"
What HTTP header do I need to send from server if authentication is NOT valid.
Do I need to set HTTP header to code 500 (ERROR)
or leave it on 200 and implement logic which checks response variable?
You don't want to send a 500 error, since that implies an unexpected server-side error that is not caused by the user.
You'll want to read up on the rfc spec for status codes:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
4XX status codes are for client errors, which is where you'll want to be looking. In your case, you could use 401 if authentication failed, and 403 if that user is not allowed to view the resource.
How about returning HTTP401?
You can handle in in AJAX error handler and redirect the whole page to login screen, if it's your requirement.
$.ajax({
statusCode: {
401: function() {
alert("User not logged in");
}
}
});