2015-06-04 54 views
0

我第一次为一个类项目构建了一个RESTful API,但是让我困惑的是某些场景的错误处理。RESTful API返回适当的错误

当客户端请求:

https://localhost:8080/api/v1/user/<username> 

我检查用户名变量无数的东西,如:

  • 如果用户名是空的或“空白”
  • 如果用户名是字母数字
  • 如果用户名的长度太短或太长

所以,我的代码看起来像这样的时刻,(这是在Python,但这是无关):

# We just grabbed the username variable 

# if the username is blank, return 404 
if not username: 
    abort(404) 
# if the username is not alphanumerical, return 404 
if not alias.isalnum(): 
    abort(404) 
# if the username length is less than 4 or greater than 25, return 404 
if len(alias) < 4 or len(alias) > 25: 
    abort(404) 

返回404错误与错误“识别”绝不看来我错了。

我应该返回404错误代码来显示出错的地方(例如“给出的用户名不是字母数字”)?

我应该返回一个不同于404的HTTP状态码吗?

我令人难以置信的困惑!

+1

使您的404页面(或甚至更好的500页面)可以接受自定义消息显示 –

+0

@NikosM模板。我曾考虑过这个问题(不是关于返回的500错误部分),但是我担心这是否是好的做法。 –

回答

1

有很多类型的HTTP状态码,您的REST API应该返回场景的正确代码。

这里是一个很好的资源: http://www.restapitutorial.com/httpstatuscodes.html

而且,用JSON有效载荷提供帮助开发商回应。这样简单的事情:

{ 
    “kind”: “error#404”, 
    “message”: string, // Give a short message about error 
    “more-info”: string // Provide more detailed error report 
} 

希望有所帮助。