พอดีไปอ่านบทความ Don’t Use If-Else and Switch in JavaScript, Use Object Literals แล้วรู้สึกว่ามันน่าสนใจ
เพราะตอนทำงานจริงๆ ผมเคยเจอบางโปรแกรมที่ handle error ด้วยการใช้ if-else, switch
if res.StatusCode >= http.StatusBadRequest { // http.StatusBadRequest = 400
// Error Log
} else {
// Info Log
}
จากโค้ด อ่านแล้วก็เข้าใจแหละ ว่า ถ้า 4xx, 5xx คือ error แต่ 1xx, 2xx, 3xx ไม่คิดจะแยกหน่อยหรอ 5555
ในความคิดผม เราควรทำตาม http standard

ก็คือ เมื่อได้ status code มาจาก 3party service ที่เราเรียก ก็ทำการ แยก level ตัวหน้าสุด นั้นทำให้คนที่มา maintain code ต่อเข้าใจได้ง่ายมากๆ
var MapPrefixStatusCode map[string]string
func init() {
MapPrefixStatusCode["1xx"] = "3party the request was received, continuing process"
MapPrefixStatusCode["2xx"] = "3party the request was successfully received, understood, and accepted"
MapPrefixStatusCode["3xx"] = "3party further action needs to be taken in order to complete the request"
MapPrefixStatusCode["4xx"] = "3party the request contains bad syntax or cannot be fulfilled"
MapPrefixStatusCode["5xx"] = "3party the server failed to fulfil an apparently valid request"
}
func prefixStatusCode(statusCodeInt int) string {
statusCode := strconv.Itoa(statusCodeInt)
if val, isExist := MapPrefixStatusCode[string(statusCode[0])+"xx"]; isExist {
return val
}
return "MapPrefixStatusCode invalid code " + statusCode
}
ทีนี้ ถ้าเราอยากจะ warp บาง error อย่าง 405 ก็ให้เราเพิ่ม mapping 405 เข้าไป
var MapStatusCode4xx map[string]string
func configStatusCode4xx(){
// 405 Method Not Allowed
MapStatusCode4xx["405"] = "Client Don't have permission to access this request"
}
ปกติ 405 คือ ไม่มี method ที่ request
แต่ทีนี้ผมไม่อยากให้ hacker หรือ client รู้ว่าผมมี method อะไรบ้าง
ผมก็เลยทำการแปลง 405 เป็น 403 แทน เพื่อบอกว่า client ไม่มีสิทธิตรงนี้นะ