forked from ebhomengo/niki
				
			feat(pkg): added err message and http message mapper
This commit is contained in:
		
							parent
							
								
									8e073db3e7
								
							
						
					
					
						commit
						092a4b308f
					
				| 
						 | 
					@ -0,0 +1,6 @@
 | 
				
			||||||
 | 
					package errmsg
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					const (
 | 
				
			||||||
 | 
						ErrorMsgNotFound           = "record not found"
 | 
				
			||||||
 | 
						ErrorMsgSomethingWentWrong = "something went wrong"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
| 
						 | 
					@ -0,0 +1,41 @@
 | 
				
			||||||
 | 
					package httpmsg
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"git.gocasts.ir/ebhomengo/niki/pkg/errmsg"
 | 
				
			||||||
 | 
						"git.gocasts.ir/ebhomengo/niki/pkg/richerror"
 | 
				
			||||||
 | 
						"net/http"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func Error(err error) (message string, code int) {
 | 
				
			||||||
 | 
						switch err.(type) {
 | 
				
			||||||
 | 
						case richerror.RichError:
 | 
				
			||||||
 | 
							re := err.(richerror.RichError)
 | 
				
			||||||
 | 
							msg := re.Message()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							code := mapKindToHTTPStatusCode(re.Kind())
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							// we should not expose unexpected error messages
 | 
				
			||||||
 | 
							if code >= 500 {
 | 
				
			||||||
 | 
								msg = errmsg.ErrorMsgSomethingWentWrong
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							return msg, code
 | 
				
			||||||
 | 
						default:
 | 
				
			||||||
 | 
							return err.Error(), http.StatusBadRequest
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func mapKindToHTTPStatusCode(kind richerror.Kind) int {
 | 
				
			||||||
 | 
						switch kind {
 | 
				
			||||||
 | 
						case richerror.KindInvalid:
 | 
				
			||||||
 | 
							return http.StatusUnprocessableEntity
 | 
				
			||||||
 | 
						case richerror.KindNotFound:
 | 
				
			||||||
 | 
							return http.StatusNotFound
 | 
				
			||||||
 | 
						case richerror.KindForbidden:
 | 
				
			||||||
 | 
							return http.StatusForbidden
 | 
				
			||||||
 | 
						case richerror.KindUnexpected:
 | 
				
			||||||
 | 
							return http.StatusInternalServerError
 | 
				
			||||||
 | 
						default:
 | 
				
			||||||
 | 
							return http.StatusBadRequest
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
		Loading…
	
		Reference in New Issue