<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("Content-Type", "application/json;charset=UTF-8")
.......................//LOGIC CODE HERE
replyData := &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("Content-Type", "application/json;charset=UTF-8")
replyData := &replyStructure{}
//LOGIC CODE HERE
jsonbytes, err := json.Marshal(replyData)
if err != nil {
// handle your error
// then write to "w"
} 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'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>{
"code": 500,
"description": "An error occurred while encoding the replyData",
"location": "restFunction"
}
</code></pre></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传