I have defined error in rust cargo 1.78.0 (54d8815d0 2024-03-26)
like this:
use thiserror::Error;
#[derive(Error, Debug)]
pub enum ChatError {
#[error("exceed llimit")]
ExceedTheChatPerDayLimit,
}
impl ChatError {
pub fn error_code(&self) -> &str {
match self {
ChatError::ExceedTheChatPerDayLimit => "0040010001",
}
}
pub fn error_message(&self) -> &str {
match self {
ChatError::ExceedTheChatPerDayLimit => "exceed limit",
}
}
pub fn error_code_en(&self) -> &str {
match self {
ChatError::ExceedTheChatPerDayLimit => "EXCEED_THE_CHAT_PER_DAY_LIMIT",
}
}
}
and then return the error to client in public function like this:
pub fn box_err_actix_rest_response(err: ChatError) -> HttpResponse{
let res = ApiResponse {
result: err.error_code_en(),
statusCode: "200".to_string(),
resultCode: err.error_code().to_string(),
msg: err.error_message().to_string(),
};
HttpResponse::Ok().json(res)
}
I want to change the error parameter to generic because I have defined other error enum like this in different module, then I tried like this:
pub fn box_err_actix_rest_response<E>(err: E) -> HttpResponse where E: thiserror::Error,{
let res = ApiResponse {
result: err.error_code_en(),
statusCode: "200".to_string(),
resultCode: err.error_code().to_string(),
msg: err.error_message().to_string(),
};
HttpResponse::Ok().json(res)
}
seems this way did not work, shows expected trait, found derive macro
thiserror::Error
, is it possible to change the error to generic that make this more flexiable with different error type? what should I do?