thiserror 0.3.2 copy "thiserror: ^0.3.2" to clipboard
thiserror: ^0.3.2 copied to clipboard

A library for concisely defining error types (error enums / sealed classes) and their String representation.

thiserror #

Pub Version Dart Package Docs License: MIT Build Status

thiserror is a library for conveniently writing Error enums (sealed classes) in Dart and is based off the Rust crate with the same name thiserror.

ThisError #

Extending the ThisError class allows you to define errors with an optional string representation possibly computed at display time.

How To Use #

Here is an example of modeling an IoError with the rust_core Result type.

sealed class IoError extends ThisError<IoError> {
  const IoError([super.stringifiable]);
}

final class IoErrorDiskRead extends IoError {
  IoErrorDiskRead(String path) : super(() => "Could not read '$path' from disk.");
}

final class IoErrorDiskWrite extends IoError {
  Object obj;

  IoErrorDiskWrite(this.obj, String path) : super(() => "Could not write '$obj' to '$path' on disk.");
}

final class IoErrorUnknown extends IoError {
  const IoErrorUnknown() : super("An unknown error occurred.");
}

Result<(), IoError> writeToDisk(Object objToWrite) {
  final diskpath = "/home/user/data_file";
  // write fails..
  final ioError = IoErrorDiskWrite(objToWrite, diskpath);
  return Err(ioError);
}

void main() {
  final result = writeToDisk("data here");
  if(result case Err(:final err)){
    switch (err) {
        case IoErrorDiskRead():
        // your code here
        case IoErrorDiskWrite(:final obj):
        // your code here
        case IoErrorUnknown():
        // your code here
        case IoErrorEmpty():
        // your code here
    }
  }
  print(result);
}

Output:

IoError: Could not write 'data here' to '/home/user/data_file' on disk.

Comparison to anyhow #

Use thiserror if you care about designing your own dedicated error type(s) so that the caller receives exactly the information that you choose in the event of failure. This most often applies to library-like code. Use anyhow if you don't care what error type your functions return, you just want it to be easy. This is common in application-like code.

2
likes
160
pub points
0%
popularity

Publisher

verified publishervoyver.com

A library for concisely defining error types (error enums / sealed classes) and their String representation.

Repository (GitHub)
View/report issues

Documentation

API reference

License

MIT (license)

More

Packages that depend on thiserror