-
I'm trying to get into the idea of new way of handling exceptions and errors with the "Error" system and got some questions:
@catch(e => e is MyError, (MyError e) => ...) Is it possible to match sub-errors by type? Or I miss some clarification on how to deal with custom errors on wiki or in other discussions? I understand that you catch base-type errors (e.g. from _ in guard<Error>(n > 0, new MyError(n))
| @catch(codeOrText, ...)
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
The reason why the codes are useful is exactly because of the matching. The codes will be compared when doing a match. This allows for localisation of text and parameterised errors (where the content of the message changes) , or sharing of codes, etc. It's also very fast. You can use Also, you only need sub-typed errors if you're going to be carrying extra data, otherwise I'd encourage you to use the What I tend to do is create an public static class Errors
{
public static readonly Error UsernameRequired = Error.New(101, "username required");
public static readonly Error PasswordRequired = Error.New(100, "password required");
public static Error ErrWithInfo(string info) => Error.New(102, "An error occurred: {info}");
public static Error ErrWithData<A>(A value) => new MyErrorType<A>(value);
} This keeps all error codes in one place, allows for pre-allocating the error type for constant errors, and it makes pattern matching relatively easy, because you can do things like this: @catch(Errors.UsernameRequired, ...)
Yep, that's a bit of an oversight, so in // Catches all Expected errors
@expected(e => ...);
// Catches all Exceptional errors
@exceptional(e => ...);
// Works with any sub-type of Error
@catchOf((YourErrorType e) => ...);
// Works with any sub-type of Exceptional
@exceptionalOf((YourErrorType e) => ...);
// Works with any sub-type of Expected
@expectedOf((YourErrorType e) => ...); The last two aren't needed really, as they can be achieved with
Obviously with the new functions you could work with the new types if you're declaring; but yes, that's a limitation. The simplification of errors to not need to declare a 100 different |
Beta Was this translation helpful? Give feedback.
The reason why the codes are useful is exactly because of the matching. The codes will be compared when doing a match. This allows for localisation of text and parameterised errors (where the content of the message changes) , or sharing of codes, etc. It's also very fast.
You can use
0
as the code if you like, then theMessage
is compared - so if you have unique error-messages it will work fine with subtypes. But I'd encourage you to leverage the codes.Also, you only need sub-typed errors if you're going to be carrying extra data, otherwise I'd encourage you to use the
Error.New(...)
variants to create errors (again leveraging the code as a discriminator rather than the type).What I ten…