golang
Cer*_*món 5
惯用的方法是检查错误返回调用链。
要从任何地方退出处理程序,请使用 panic 并按照encoding/json 包中的模式恢复。
为恐慌定义一个独特的类型:
type httpError struct { status int message string}编写要在 defer 语句中使用的函数。该函数检查类型并酌情处理错误。否则,该函数将继续恐慌。
func handleExit(w http.ResponseWriter) { if r := recover(); r != nil { if he, ok := r.(httpError); ok { http.Error(w, he.message, he.status) } else { panic(r) } }}为 panic 的调用编写一个辅助函数:
func exit(status int, message string) { panic(httpError{status: status, message: message})}使用如下函数:
func example() { exit(http.StatusBadRequest, "Bad!")}func someHandler(w http.ResponseWriter, r *http.Request) { defer handleExit(w) example()}golang