Skip to content

Commit

Permalink
Add a simple Debug impl for Error (#248)
Browse files Browse the repository at this point in the history
* Add a simple Debug impl for Error
* Drop unneeded ok() calls
  • Loading branch information
filmor authored Oct 16, 2019
2 parents eba1d3d + a87604f commit 9624f53
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
16 changes: 13 additions & 3 deletions rustler/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use crate::codegen_runtime::{NifReturnable, NifReturned};
use crate::{types, Encoder, Env};
use std::fmt;

/// Represents usual errors that can happen in a nif. This enables you
/// to return an error from anywhere, even places where you don't have
/// an Env availible.
/// an Env available.
pub enum Error {
/// Returned when the NIF has been called with the wrong number or type of
/// arguments.
Expand All @@ -20,14 +21,12 @@ unsafe impl NifReturnable for crate::error::Error {
Error::BadArg => NifReturned::BadArg,
Error::Atom(atom_str) => {
let atom = types::atom::Atom::from_str(env, atom_str)
.ok()
.expect("Error::Atom: bad atom")
.to_term(env);
NifReturned::Term(atom.as_c_arg())
}
Error::RaiseAtom(atom_str) => {
let atom = types::atom::Atom::from_str(env, atom_str)
.ok()
.expect("Error::RaiseAtom: bad argument");
NifReturned::Raise(atom.as_c_arg())
}
Expand All @@ -38,3 +37,14 @@ unsafe impl NifReturnable for crate::error::Error {
}
}
}

impl fmt::Debug for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match self {
Error::BadArg => write!(fmt, "{{error, badarg}}"),
Error::Atom(ref s) => write!(fmt, "{{error, {}}}", s),
Error::RaiseAtom(ref s) => write!(fmt, "throw({})", s),
Error::RaiseTerm(_) => write!(fmt, "throw(<term>)"),
}
}
}
2 changes: 1 addition & 1 deletion rustler/src/types/atom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ macro_rules! rustler_atoms {
};
{ @internal_make_atom($env:ident, $name:ident = $str:expr) } => {
$crate::types::atom::Atom::from_str($env, $str)
.ok().expect("rustler::atoms!: bad atom string")
.expect("rustler::atoms!: bad atom string")
};
}

Expand Down

0 comments on commit 9624f53

Please sign in to comment.