HttpResponseException
如果 Web API 的 controller 擲出一個例外(exception),會發生什麼事?預設下,最常是會把例外轉譯為一個 HTTP 狀態碼 500 (Internal Server Error) 回應。
HttpResponseException 型別是一個特別情況。你能指定此例外的建構式,這個例外能回傳任何 HTTP 狀態碼。例如,下面例子,如果 id 參數不存在,會回傳 404 (Not Found) 狀態碼。
Function GetContact(id As Integer) As Contact Dim contact As Contact = _repository.GetContactById(id) If contact Is Nothing Then Throw New HttpResponseException(System.Net.HttpStatusCode.NotFound) End If Return contact End Function
想要對回應取得更多控制,你也能建構回應的訊息 (HttpResponseMessage 型別),然後包含在 HttpResponseException 裡:
Function GetContact(id As Integer) As Contact Dim contact As Contact = _repository.GetContactById(id) If contact Is Nothing Then ' Throw New HttpResponseException(System.Net.HttpStatusCode.NotFound) Dim msg As New HttpResponseMessage(System.Net.HttpStatusCode.NotFound) msg.Content = New StringContent( String.Format("無法找到連絡人ID = {0}", id)) msg.ReasonPhrase = "未發現連絡人" Throw New HttpResponseException(msg) End If Return contact End Function