HandleError handles an error by sending it to the client based on the registered error code names and their error functions. Returns true if the error was handled, otherwise false. If the given "err" is nil then it returns false. If the given "err" is a type of validation error then it sends it to t
(ctx *context.Context, err error)
| 141 | // |
| 142 | // See ErrorCodeName.MapErrorFunc and MapErrors methods too. |
| 143 | func HandleError(ctx *context.Context, err error) bool { |
| 144 | if err == nil { |
| 145 | return false |
| 146 | } |
| 147 | |
| 148 | if ctx.IsStopped() { |
| 149 | return false |
| 150 | } |
| 151 | |
| 152 | for errorCodeName, errorFuncs := range errorFuncCodeMap { |
| 153 | for _, errorFunc := range errorFuncs { |
| 154 | if errToSend := errorFunc(err); errToSend != nil { |
| 155 | errorCodeName.Err(ctx, errToSend) |
| 156 | return true |
| 157 | } |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | // Unwrap and collect the errors slice so the error result doesn't contain the ErrorCodeName type |
| 162 | // and fire the error status code and title based on this error code name itself. |
| 163 | var asErrCode ErrorCodeName |
| 164 | if As(err, &asErrCode) { |
| 165 | if unwrapJoined, ok := err.(joinedErrors); ok { |
| 166 | errs := unwrapJoined.Unwrap() |
| 167 | errsToKeep := make([]error, 0, len(errs)-1) |
| 168 | for _, src := range errs { |
| 169 | if _, isErrorCodeName := src.(ErrorCodeName); !isErrorCodeName { |
| 170 | errsToKeep = append(errsToKeep, src) |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | if len(errsToKeep) > 0 { |
| 175 | err = errors.Join(errsToKeep...) |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | asErrCode.Err(ctx, err) |
| 180 | return true |
| 181 | } |
| 182 | |
| 183 | if handleJSONError(ctx, err) { |
| 184 | return true |
| 185 | } |
| 186 | |
| 187 | if vErr, ok := err.(ValidationError); ok { |
| 188 | if vErr == nil { |
| 189 | return false // consider as not error for any case, this should never happen. |
| 190 | } |
| 191 | |
| 192 | InvalidArgument.Validation(ctx, vErr) |
| 193 | return true |
| 194 | } |
| 195 | |
| 196 | if vErrs, ok := err.(ValidationErrors); ok { |
| 197 | if len(vErrs) == 0 { |
| 198 | return false // consider as not error for any case, this should never happen. |
| 199 | } |
| 200 |
no test coverage detected
searching dependent graphs…