Reputation: 829
I need to handle errors with error code and return errors in JSON format like below.
{
"errorCode":400,
"errors":[
{
"errorField":"dispachNumber",
"errorDescription": "This is not a valid dispatch Number"
},
{
"errorField":"phone",
"errorDescription": "Phone numbers must be in the XXX-XXX-XXXX format"
}
]
}
{
"errorCode":500,
"errors":[
{
"errorDescription": "there was an internal server error"
}
]
}
My problem is how to handle this way , here i am able to do with single error only but when i do with multiple errors it return only one error struct , see code how i am doing this.
Errors := ErrorHandle(403, "User Id", "User Id must be of integer type")
Errors = ErrorHandle(403, "Phone Number", "Phone Number type")
and ErrorHandle()
function as
func ErrorHandle(ErrorCode int, ErrorFields, ErrorDesc string) []Errors {
AllErrors := []Errors{}
if len(AllErrors) > 0 {
AllErrors = IterateErrors(AllErrors, ErrorCode, ErrorFields, ErrorDesc)
} else {
Errorsvalue := Errors{
ErrorCode: ErrorCode,
}
Error := Error{}
Error.ErrorFields = ErrorFields
Error.ErrorDescription = ErrorDesc
Errorsvalue.ErrorDesc = append(Errorsvalue.ErrorDesc, Error)
AllErrors = append(AllErrors, Errorsvalue)
}
return AllErrors
}
Thanks in Advance !
Upvotes: 0
Views: 739
Reputation: 21035
You're always creating a new empty AllErrors
slice, adding a single error to it, then returning it.
Your ErrorHandle
should either take the existing list of errors and append to it or you should have a custom type Errors []Error
used as such:
type Errors []Error
func (Errors *e) ErrorHandle(...) {
...
e = append(e, <new error>)
}
Errors myerrors;
myerrors.ErrorHandle(<first error>)
myerrors.ErrorHandle(<second error>)
This is just high-level code, you should be able to fill in the rest.
Upvotes: 2