Skip to content

Commit

Permalink
better errors
Browse files Browse the repository at this point in the history
  • Loading branch information
aine-etke committed Aug 28, 2024
1 parent 984df56 commit 7f02297
Showing 1 changed file with 15 additions and 9 deletions.
24 changes: 15 additions & 9 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package kit

import (
"encoding/json"
"fmt"
"io"
)

Expand All @@ -18,12 +19,12 @@ func (e ErrorResponse) Error() string {
}

// NewErrorResponse creates a new error response
func NewErrorResponse(err error) ErrorResponse {
func NewErrorResponse(err error) *ErrorResponse {
if err == nil {
return ErrorResponse{Err: "unknown error"}
return &ErrorResponse{Err: "unknown error"}
}

return ErrorResponse{Err: err.Error()}
return &ErrorResponse{Err: err.Error()}
}

// MatrixError represents an error response from the Matrix API
Expand All @@ -38,15 +39,20 @@ func (e MatrixError) Error() string {
}

// NewMatrixError creates a new Matrix error
func NewMatrixError(code, err string) MatrixError {
return MatrixError{Code: code, Err: err}
func NewMatrixError(code, err string) *MatrixError {
return &MatrixError{Code: code, Err: err}
}

// MatrixErrorFrom creates a new Matrix error from io.Reader
func MatrixErrorFrom(r io.Reader) MatrixError {
var matrixErr MatrixError
if err := json.NewDecoder(r).Decode(&matrixErr); err != nil {
return NewMatrixError("M_UNKNOWN", err.Error())
func MatrixErrorFrom(r io.Reader) *MatrixError {
if r == nil {
return nil
}

var matrixErr *MatrixError
data, _ := io.ReadAll(r) //nolint:errcheck // ignore error as we will return nil
if err := json.Unmarshal(data, &matrixErr); err != nil {
return NewMatrixError("M_UNKNOWN", fmt.Sprintf("failed to decode error response %q: %v", string(data), err))
}

return matrixErr
Expand Down

0 comments on commit 7f02297

Please sign in to comment.