为什么后端开发都喜欢自己定义 responseCode? HTTP 状态码不够用吗?

61 阅读2分钟

这个主要是我在开发时对于 这个responseCode有点疑惑,毕竟这里面的状态码可能大部分HTTP状态码都实现了,于是谷歌到这个问题,实际上和我有相同疑惑的人不在少数,看看他们是怎么回答的。www.v2ex.com/t/676678?p=…

实际上HTTP状态码有很多,简单看看MDN上的定义developer.mozilla.org/zh-CN/docs/…

列出来大概是这么多

declare enum HttpStatusCode {
  Continue = 100,
  SwitchingProtocols = 101,
  Processing = 102,
  EarlyHints = 103,
  Ok = 200,
  Created = 201,
  Accepted = 202,
  NonAuthoritativeInformation = 203,
  NoContent = 204,
  ResetContent = 205,
  PartialContent = 206,
  MultiStatus = 207,
  AlreadyReported = 208,
  ImUsed = 226,
  MultipleChoices = 300,
  MovedPermanently = 301,
  Found = 302,
  SeeOther = 303,
  NotModified = 304,
  UseProxy = 305,
  Unused = 306,
  TemporaryRedirect = 307,
  PermanentRedirect = 308,
  BadRequest = 400,
  Unauthorized = 401,
  PaymentRequired = 402,
  Forbidden = 403,
  NotFound = 404,
  MethodNotAllowed = 405,
  NotAcceptable = 406,
  ProxyAuthenticationRequired = 407,
  RequestTimeout = 408,
  Conflict = 409,
  Gone = 410,
  LengthRequired = 411,
  PreconditionFailed = 412,
  PayloadTooLarge = 413,
  UriTooLong = 414,
  UnsupportedMediaType = 415,
  RangeNotSatisfiable = 416,
  ExpectationFailed = 417,
  ImATeapot = 418,
  MisdirectedRequest = 421,
  UnprocessableEntity = 422,
  Locked = 423,
  FailedDependency = 424,
  TooEarly = 425,
  UpgradeRequired = 426,
  PreconditionRequired = 428,
  TooManyRequests = 429,
  RequestHeaderFieldsTooLarge = 431,
  UnavailableForLegalReasons = 451,
  InternalServerError = 500,
  NotImplemented = 501,
  BadGateway = 502,
  ServiceUnavailable = 503,
  GatewayTimeout = 504,
  HttpVersionNotSupported = 505,
  VariantAlsoNegotiates = 506,
  InsufficientStorage = 507,
  LoopDetected = 508,
  NotExtended = 510,
  NetworkAuthenticationRequired = 511,
}

其实不难发现,这些都是在传输时定义的状态码,它大概率只能解释传输中的问题,比如你的服务是否正常返回一个200,你的服务不正常,返回一个404或者其他。而后端自定义的responseCode主要是为了定义业务问题,例如

const errCode = {
  40000: '请求参数错误',
  40001: '请求数据为空',
  40100: '未登录',
  40101: '无权限',
  40301: '访问屏蔽',
  50000: '系统内部异常',
}

简单来说,HTTP是传输层的定义,而responseCode是业务层的定义,二者互不相干。