2015-06-04 60 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 
} 

希望有所幫助。