I have a struct with some functions and when something goes wrong I call a function fn set_error(&self,msg:&str) to log the error and possible show an error message etc.
Currently this is very simple and I use it like following in other functions:
pub fn somefunction(&self) {
...some code...
if error == true {
self.set_error("The error message");
Err("The error message")
}else{
Ok("All ok")
}
}
To begin with it could be useful for the set_error()-function to return a Result::Error object in some way so calling set_error() would be the same as:
self.set_error("The error message");
Err("The error message")
Another way could be to return the error-string again from the set_error()-function to be able to do:
Err( self.set_error("The error message") )
Also, is there a simple/nice way to join/concat strings (String, &str etc) that is sent to the set_error()-function? For example, in match-Err there could be a std::io::error and maybe a u32 where I would like to do:
self.set_error("A lvl 10 Error occured: " + err.to_string() + ". UserId:" + user_id.to_string() + ". Some other info...");
This thought is taken from PHP where that can be done to create the error string in the call to the function in a simple way.
How would a set_error()-function look to handle error in my scenario and how would I build an error-message, sent to set_error(), in a good way?
More info:
Doing self.set_error(format!("..Error..: {err}. UserId:{user_id}.")), as suggested by user4815162342, results in problems when trying to do: return Err( self.set_error(format!("..Error..: {err}. UserId:{user_id}.")) );.
This is since Err() need a &str and if I change self.set_error to return &str then that &str only lives in the function and can't be used outside it.
If trying to do
fn set_error(&self,msg:String) -> String {
println!("Err: {msg}");
msg
}
...
return Err(self.set_error(format!("..Error..: {err}. UserId:{user_id}.").as_str());
...
Then I get:
cannot return value referencing temporary value.
returns a value referencing data owned by the current function.
So how would the set_error()-function look to be able to do:
return Err(self.set_error(format!("..Error..: {err}. UserId:{user_id}.")); or similar?
I'm not looking to get exactly this to work but to get something easy to use to work.
set_error()would receive amsg: impl Into<String>. That way you can call it with a string literal, as before, but also with a dynamically generated string, which you create with the usualformat!(), e.g.:self.set_error(format!("A lvl 10 Error occurred: {err}. UserId:{user_id}. Some other info...")). Convenience level comparable to PHP.String, not a&str.