-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Introduce dedicated custom error types for improved user-experience
- Loading branch information
Showing
1 changed file
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |