Recommended failure to write to REST reply

blov · · 49 次点击    
<p>Hi, I have a simple question in what do people do in the following case, take the following code as an example:</p> <pre><code>func restFuncion(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() w.Header().Set(&#34;Content-Type&#34;, &#34;application/json;charset=UTF-8&#34;) .......................//LOGIC CODE HERE replyData := &amp;replyStructure{} err := json.NewEncoder(w).Encode(replyData) } </code></pre> <p>So, in the case that the Encode fails, I have the following options, a. Ignore it as it is the last line, and if I cannot write to the writer, I cannot really tell the request. (and probably log it) b. Try and write something else to the writer, like for example, some simple text ? c. Return a HTTP status code instead, however, the logic above may have already written something to the writer in the process too maybe ?</p> <p>What are other peoples recommendations ?</p> <p>Thanks in advance for your input.</p> <hr/>**评论:**<br/><br/>iroflmaowtf: <pre><p>why would you create a new encoder for each request? you could use json.Marshal(...) followed by w.write(marshaledBytes), in this way, err will be caught before writing to the response interface, example:</p> <pre><code>func restFunc(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() w.Header().Set(&#34;Content-Type&#34;, &#34;application/json;charset=UTF-8&#34;) replyData := &amp;replyStructure{} //LOGIC CODE HERE jsonbytes, err := json.Marshal(replyData) if err != nil { // handle your error // then write to &#34;w&#34; } else { w.write(jsonbytes); } } </code></pre></pre>janderssen: <pre><p>Thanks, this makes total sense.</p></pre>Kraigius: <pre><p>Since you are speaking in the case that your own reply message fails to properly encode, it is considered a server error. Reply with code 500 Internal Server Error. Do log the error along with some contextual information to help you track the problem.</p> <p>I would consider it a bad practice to write something that isn&#39;t expected by the client (option b). Consider implementing an error response type across your application that way you will have all the necessary information at hand and clients can expect and correctly handle your reply. </p> <p>ie:</p> <pre><code>{ &#34;code&#34;: 500, &#34;description&#34;: &#34;An error occurred while encoding the replyData&#34;, &#34;location&#34;: &#34;restFunction&#34; } </code></pre></pre>
49 次点击  
加入收藏 微博
0 回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传