Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

REST API状态码设计 #4

Open
hstarorg opened this issue Jun 27, 2017 · 0 comments
Open

REST API状态码设计 #4

hstarorg opened this issue Jun 27, 2017 · 0 comments

Comments

@hstarorg
Copy link
Owner

正常请求

直接返回具体的业务数据,HTTP状态码根据具体的场景列举如下:

  • 200 最常用,返回数据
  • 201 如果是创建资源成功,则使用201
  • 202 如果是更新或删除资源成功,则使用202
  • 204 不想返回任何内容,则可以使用204

异常请求

业务异常

  • 400 错误的请求,可能是参数不对
  • 401 未授权
  • 403 禁止访问
  • 404 找不到资源

服务端标准错误

  • 500 直接扔标准的500错误

异常数据格式

{
    status: 401, // 和HTTP状态码一致
    code: '201452', // 业务定义的错误代码
    message: 'Unauthorized', // 错误信息
    stack: null // 区分环境,确认是否输出
}

附Express中的错误处理逻辑:

app.use((req, res, next) => {
  next({
    status: 404,
    code: '404',
    message: '404 Not Found.'
  });
});
app.use((err, req, res, next) => {
  let status = 500;
  let message = '';
  let code = '500';
  let stack = null;
  // 简单业务错误
  if (typeof err === 'string') {
    status = 400;
    code = '400';
    message = err;
  } else if (err.isJoi) {// 请求验证错误
    status = 400;
    code = '400';
    message = err.details.map(x => x.message).join('\n');
  } else if (err instanceof Error) { // 标准错误处理
    if (err.code) {
      code = err.code;
    }
    message = err.message;
    stack = err.stack;
  } else { // Next({status: 400, code: 'xxx'}) 自定义错误
    status = err.status || 400;
    code = err.code || '400';
    message = err.message;
  }
  res.status(status).json({
    status,
    code,
    message,
    stack
  });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant