rspack_error/
convert.rs

1use miette::SourceOffset;
2
3use crate::{
4  Result,
5  error::{Error, Label},
6};
7
8pub trait ToStringResultToRspackResultExt<T, E: ToString> {
9  fn to_rspack_result(self) -> Result<T>;
10  fn to_rspack_result_with_message(self, formatter: impl FnOnce(E) -> String) -> Result<T>;
11}
12
13impl<T, E: ToString> ToStringResultToRspackResultExt<T, E> for std::result::Result<T, E> {
14  fn to_rspack_result(self) -> Result<T> {
15    self.map_err(|e| crate::error!(e.to_string()))
16  }
17  fn to_rspack_result_with_message(self, formatter: impl FnOnce(E) -> String) -> Result<T> {
18    self.map_err(|e| crate::error!(formatter(e)))
19  }
20}
21
22pub trait SerdeResultToRspackResultExt<T> {
23  fn to_rspack_result_with_detail(self, content: &str, msg: &str) -> Result<T>;
24}
25
26impl<T> SerdeResultToRspackResultExt<T> for std::result::Result<T, serde_json::Error> {
27  fn to_rspack_result_with_detail(self, content: &str, msg: &str) -> Result<T> {
28    self.map_err(|e| {
29      let offset = SourceOffset::from_location(content, e.line(), e.column());
30      let mut error = Error::error(msg.into());
31      error.labels = Some(vec![Label {
32        name: Some(e.to_string()),
33        offset: offset.offset(),
34        len: 0,
35      }]);
36      error.src = Some(content.to_string());
37      error
38    })
39  }
40}
41
42pub trait AnyhowResultToRspackResultExt<T> {
43  fn to_rspack_result_from_anyhow(self) -> Result<T>;
44}
45
46impl<T> AnyhowResultToRspackResultExt<T> for std::result::Result<T, anyhow::Error> {
47  fn to_rspack_result_from_anyhow(self) -> Result<T> {
48    self.map_err(|e| e.into())
49  }
50}