搜索插件、代码仓与 APP 分类

插件详情v3.0.1

anyhow

惯用的错误处理功能,让您的代码更安全、更易维护,并且更容易调试。Dart 对 Rust 的 Result 单子类型和 "anyhow" crate 的实现。

AndroidiOSWebmacOSWindowsLinux
近 30 天下载
698
喜欢数
32
Pub 分数
150

安装插件

flutter pub add anyhow

插件介绍

基于插件公开信息、社区数据与项目使用情况整理的选型参考。

anyhow 包为 Dart 提供了符合习惯的错误处理方式,灵感来自 Rust 的 Result 单子和 'anyhow' crate。它通过允许开发者以更富表现力和可组合的方式返回和处理错误,简化了错误传播和管理。该包内置了上下文添加和堆栈跟踪支持,增强了调试能力并提高了代码可维护性。该包旨在使所有平台上的错误处理感觉自然且安全。

适合场景

  • 简化异步操作中的错误处理
  • 向错误中添加上下文信息
  • 提高故障点的可调试性
  • 编写更安全且更易读的代码
  • 统一处理多种错误类型

主要特点

  • 结果单子模式
  • 自动堆栈跟踪捕获
  • 上下文错误包装
  • 与 Dart 的 async/await 无缝集成
  • 最小化样板代码

适合对象

  • 寻求类似 Rust 错误处理的开发者
  • 需要详细错误诊断的项目
  • 注重代码可维护性的团队
  • 具有复杂错误流程的应用程序
  • 跨平台 Flutter 应用

使用建议

  • 可能对初学者带来学习曲线
  • 并非在所有情况下都能替代 try-catch
  • 需要理解函数式错误模式
  • 限制为非可空上下文
  • 最好与适当的日志记录结合使用

原始 README

以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。

anyhow

Pub Version Dart Package Docs License: MIT Build Status

anyhow offers versatile and idiomatic error handling capabilities to make your code safer, more maintainable, and errors easier to debug.

This is accomplished through the use of the Result monad type and an implementation of the popular Rust crate with the same name - anyhow. anyhow will allow you to never throw another exception again and have a predictable control flow. When errors do arise, you can add context to better understand the situation that led to the errors. See here to jump right into an example.

What Is a Result Monad Type And Why Use it?

If you are not familiar with the Result type, why it is needed, or it's usages, you can read up on all that here: article

The Better Way To Handle Errors With Anyhow

Before anyhow, with a regular Result type, we had no way to know the context around Errs. anyhow fixes this and more! With the anyhow Result type, we can now add any Object as context around errors. To do so, we can use context or withContext (lazily). Either will only have an effect if a Result is the Err subclass. In the following example we will use Strings as the context, but using Exceptions, especially for the root cause is common practice as well.

import 'package:anyhow/anyhow.dart';

void main() {
  print(order("Bob", 1));
}

Result<String> order(String user, int orderNumber) {
  final result = makeFood(orderNumber).context("Could not order for $user.");
  if(result case Ok(v:final order)) {
    return Ok("Order of $order is complete for $user");
  }
  return result;
}

Result<String> makeFood(int orderNumber) {
  if (orderNumber == 1) {
    return makePizza().context("Order was number $orderNumber.");
  }
  return Ok("pasta");
}

Result<String> makePizza() {
  return bail("Pizza was missing a topping.");
}
Output
Could not order for Bob.

Caused By:
	0: Order was number 1.
	1: Pizza was missing a topping..
	
StackTrace:
#0      AnyhowResultExtensions.context (package:anyhow/src/anyhow/anyhow_extensions.dart:12:29)
#1      order (package:anyhow/test/src/temp.dart:9:40)
#2      main (package:anyhow/example/main.dart:5:9)
... <OMITTED FOR EXAMPLE>

Now we know keep a record of exactly what was happening at each level in the call stack!

What Would This Look Like Without Anyhow

Before anyhow, if we wanted to accomplish something similar with Result, we had to do:

void main() {
  print(order("Bob", 1));
}

Result<String, String> order(String user, int orderNumber) {
  final result = makeFood(orderNumber);
  if(result case Ok(v:final order)) {
    return Ok("Order of $order is complete for $user");
  }
  Logging.w("Could not order for $user.");
  return result;
}

Result<String, String> makeFood(int orderNumber) {
  if (orderNumber == 1) {
    final result = makePizza();
    if (result.isErr()) {
      Logging.w("Order was number $orderNumber.");
    }
    return result;
  }
  return Ok("pasta");
}

Result<String, String> makePizza() {
  // What is the context around this error??
  return Err("Pizza was missing a topping.");
}

Which is more verbose/error-prone and may not be what we actually want. Since:

  1. We may not want to log anything if the error state is known and can be recovered from
  2. Related logs should be kept together (in the example, other functions could log before this Result had been handled)
  3. We have no way to get the correct stack traces related to the original issue
  4. We have no way to inspect "context", while with anyhow we can iterate through with chain()

Now with anyhow, we are able to better understand and handle errors in an idiomatic way!

Configuration Options

anyhow functionality can be changed by changing:

Error.hasStackTrace;
Error.displayOrder;
Error.stackTraceDisplayFormat;
Error.stackTraceDisplayModifier;

Which is usually done at startup.

  • hasStackTrace: With Error.hasStackTrace = false, we can exclude capturing a stack trace:
Could not order for Bob.

Caused By:
	0: Order was number 1.
	1: Pizza was missing a topping.
  • displayOrder: We can view the root cause first with Error.displayOrder = ErrorDisplayOrder.rootFirst
Pizza was missing a topping.

Additional Context:
	0: Order was number 1.
	1: Could not order for Bob.

StackTrace:
#0      bail (package:anyhow/src/anyhow/functions.dart:6:14)
#1      makePizza (package:anyhow/test/src/temp.dart:31:10)
... <OMITTED FOR EXAMPLE>
  • stackTraceDisplayFormat: if we want to include none, the main, or all stacktraces in the output.

  • stackTraceDisplayModifier: Modifies the stacktrace during display. Useful for adjusting number of frames to include during display/logging.

Anyhow Result Type vs Rust Result Type

The Result type for this package is just a typedef of the Result type in the rust package. Thus inheriting all capabilities and the two types/packages can be used seamlessly together -

import 'package:anyhow/anyhow.dart' as anyhow;
import 'package:rust/rust.dart';

void main(){
  Result<int,anyhow.Error> x = Ok(1);
  x.context(2);
  anyhow.Result<int> y = Ok(1);
  y.context(2);
  assert(x == y);
  Cell(1); // e.g. `rust` package type
}

or

import 'package:anyhow/rust.dart'; // overlays anyhow on top of the `rust` package

void main(){
  Result<int> x = Ok(1);
  x.context(1);
  Cell(1); // e.g. `rust` package type
}

Downcasting

Downcasting is the process of getting the inner error from an an anyhow Error.

import 'package:anyhow/anyhow.dart';

void main(){
  Result<int> x = bail("this is an error message");
  Error error = x.unwrapErr();
  assert(error.downcast<String>().unwrap() == "this is an error message");
  assert(error.downcastUnchecked() == "this is an error message"); // or
}

This may be useful when you want to inspect the root error type.

import 'package:anyhow/anyhow.dart';

void main(){
  Result<int> x = bail("this is an error message").context(1);
  final rootInner = x.unwrapErr().rootCause().downcastUnchecked();
  switch(rootInner) {
    case String():
      print("String found");
    default:
      print("Default reached");
  }
}

Since anyhow makes the trade off that you do not care about the underlying causes inner type, which allows your api's to be more composable and concise, downcasting is expected to be used sparingly.

所属分类

依赖

依赖清单 1 项

源码仓库

使用此插件的项目

暂无相关数据。