I am getting myself confused between code
and status
working with Node.js and Express.
When I create an Error()
I do this for example:
const Err = new Error();
Err.message = "Login failed";
Err.code = 401; // why is this not Err.statusCode or Err.status ?
throw(Err);
Returning that via Express ends up becoming:
catch (error) {
return res.status(error.code).send(error.message);
}
The Express.js documentation says that res.status
is an alias of Node's response.statusCode .
So why is the same code expressed in three different ways: error.code
, response.statusCode
and res.status
. Why isn't it consistently the same?
Essentially the code
and status
you're talking about refer to two different concepts.
1 - The Error
class code
property refers to a standard node.js concept and is not http-specific - just like the Error
class iteself.
This is what node's documentation says about it:
The error.code property is a string label that identifies the kind of error.
If you want an Error
object representing a http error to actually hold a http status information, then nothing prevents you from adding a dedicated custom status
- or statusCode
- property. A httpError
value for the code
property would probably be more fitting in this case since it refers to a higher-level concept than a more fine-grained http status.
2 - response.statusCode
and response.status
on the other hand are both http specific and relate to the http status of a http.ServerResponse
object. The http.ServerResponse
class is defined by node.js, and res.status
is just a shorthand setter that is added by express for conveniency - and couldn't possibly be named after the same name as the property it serves as a setter for.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.