Skip to content

Commit

Permalink
Introduce dedicated custom error types for improved user-experience
Browse files Browse the repository at this point in the history
  • Loading branch information
oleiade committed Jul 7, 2023
1 parent 03c3ab4 commit a27c795
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions js/modules/k6/experimental/fs/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package fs

import "fmt"

// NewError creates a new Error object of the provided kind and with the
// provided message.
func NewError(k ErrorKind, message string) *Error {
return &Error{
Name: k,
Message: message,
}
}

// ErrorKind is a type alias for the kind of an error.
//
// Note that this is defined as a type alias, and not a binding, so
// that it is not interpreted as an object by goja.
type ErrorKind = string

const (
// NotFoundError is emitted when a file is not found.
NotFoundError ErrorKind = "NotFoundError"

// InvalidResourceError is emitted when a resource is invalid: for
// instance when attempting to open a directory, which is not supported.
InvalidResourceError ErrorKind = "InvalidResourceError"

// ForbiddenError is emitted when an operation is forbidden.
ForbiddenError ErrorKind = "ForbiddenError"

// TypeError is emitted when an incorrect type has been used.
TypeError ErrorKind = "TypeError"
)

// Error represents a custom error object emitted by the fs module.
type Error struct {
// Name contains the name of the error as formalized by the [ErrorKind]
// type.
Name ErrorKind `json:"name"`

// Message contains the error message as presented to the user.
Message string `json:"message"`
}

// Ensure that the Error type implements the Go `error` interface.
var _ error = (*Error)(nil)

// Error implements the Go `error` interface.
func (e *Error) Error() string {
return fmt.Sprintf(e.Name)
}

0 comments on commit a27c795

Please sign in to comment.