FFI中的错误处理

说明

在像C语言这种,错误是用返回码表示的。然而,Rust的类型系统支持通过一个完整的类型来提供更加丰富的错误信息。

下面的实践展示了错误代码的不同类型,以及如何在使用层面上去暴露它们:

  1. 扁平的枚举(译者注:无实际的成员数据)转换成整型并且作为错误码返回。
  2. 结构体枚举应该被转换为一个整型错误码和一个包含详细错误信息的字符串。
  3. 自定义错误类型应该被转换为C语言标准下的表示类型。

代码示例

扁平枚举

  1. enum DatabaseError {
  2. IsReadOnly = 1, // user attempted a write operation
  3. IOError = 2, // user should read the C errno() for what it was
  4. FileCorrupted = 3, // user should run a repair tool to recover it
  5. }
  6. impl From<DatabaseError> for libc::c_int {
  7. fn from(e: DatabaseError) -> libc::c_int {
  8. (e as i8).into()
  9. }
  10. }

结构体枚举

  1. pub mod errors {
  2. enum DatabaseError {
  3. IsReadOnly,
  4. IOError(std::io::Error),
  5. FileCorrupted(String), // message describing the issue
  6. }
  7. impl From<DatabaseError> for libc::c_int {
  8. fn from(e: DatabaseError) -> libc::c_int {
  9. match e {
  10. DatabaseError::IsReadOnly => 1,
  11. DatabaseError::IOError(_) => 2,
  12. DatabaseError::FileCorrupted(_) => 3,
  13. }
  14. }
  15. }
  16. }
  17. pub mod c_api {
  18. use super::errors::DatabaseError;
  19. #[no_mangle]
  20. pub extern "C" fn db_error_description(
  21. e: *const DatabaseError
  22. ) -> *mut libc::c_char {
  23. let error: &DatabaseError = unsafe {
  24. // SAFETY: pointer lifetime is greater than the current stack frame
  25. &*e
  26. };
  27. let error_str: String = match error {
  28. DatabaseError::IsReadOnly => {
  29. format!("cannot write to read-only database");
  30. }
  31. DatabaseError::IOError(e) => {
  32. format!("I/O Error: {}", e);
  33. }
  34. DatabaseError::FileCorrupted(s) => {
  35. format!("File corrupted, run repair: {}", &s);
  36. }
  37. };
  38. let c_error = unsafe {
  39. // SAFETY: copying error_str to an allocated buffer with a NUL
  40. // character at the end
  41. let mut malloc: *mut u8 = libc::malloc(error_str.len() + 1) as *mut _;
  42. if malloc.is_null() {
  43. return std::ptr::null_mut();
  44. }
  45. let src = error_str.as_bytes().as_ptr();
  46. std::ptr::copy_nonoverlapping(src, malloc, error_str.len());
  47. std::ptr::write(malloc.add(error_str.len()), 0);
  48. malloc as *mut libc::c_char
  49. };
  50. c_error
  51. }
  52. }

自定义错误类型

  1. struct ParseError {
  2. expected: char,
  3. line: u32,
  4. ch: u16
  5. }
  6. impl ParseError { /* ... */ }
  7. /* Create a second version which is exposed as a C structure */
  8. #[repr(C)]
  9. pub struct parse_error {
  10. pub expected: libc::c_char,
  11. pub line: u32,
  12. pub ch: u16
  13. }
  14. impl From<ParseError> for parse_error {
  15. fn from(e: ParseError) -> parse_error {
  16. let ParseError { expected, line, ch } = e;
  17. parse_error { expected, line, ch }
  18. }
  19. }

优点

这样能确保其他语言能够正确访问错误信息,并且不用为此改动Rust代码的API。(译者注:相当于在错误处理时再封装一层,返回最简单的整型和字符串作为错误信息表示)

缺点

这样多写了很多代码,并且有些类型不能很容易地转换成C语言的标准。