1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
//! An example to handle error with signing in.
//!
//! ```shell
//! $ cargo run --example handle_error -- --email <email> --password <password>
//! ```
use clap::Parser;
use fars::error::CommonErrorCode;
use fars::ApiKey;
use fars::Config;
use fars::Email;
use fars::Password;
#[derive(Parser)]
struct Arguments {
#[arg(short, long)]
email: String,
#[arg(short, long)]
password: String,
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Parse the command line arguments.
let arguments = Arguments::parse();
// Read API key from the environment variable.
let api_key = ApiKey::new(std::env::var("FIREBASE_API_KEY")?);
// Create a config.
let config = Config::new(api_key);
// Create a session by signing in with email and password.
match config
.sign_in_with_email_password(
Email::new(arguments.email.clone()),
Password::new(arguments.password.clone()),
)
.await
{
// Success
| Ok(session) => {
println!(
"Succeeded to sign in with email/password: {:?}",
session
);
// Do something with the session.
Ok(())
},
// Failure
| Err(error) => {
match error {
// Handle HTTP request error.
| fars::Error::HttpRequestError(error) => {
println!("HTTP request error: {:?}", error);
// Do something with HTTP request error, e.g. retry.
Err(error.into())
},
// Handle API error.
| fars::Error::ApiError {
status_code,
error_code,
response,
} => {
match error_code {
| CommonErrorCode::InvalidLoginCredentials => {
eprintln!("Invalid email and/or password.");
// Do something with invalid login credentials, e.g. display error message for user.
Err(fars::Error::ApiError {
status_code,
error_code,
response,
}
.into())
},
| CommonErrorCode::UserDisabled => {
eprintln!("This user is disabled.");
// Do something with disabled user, e.g. display error message for user.
Err(fars::Error::ApiError {
status_code,
error_code,
response,
}
.into())
},
| CommonErrorCode::TooManyAttemptsTryLater => {
eprintln!("Too many attempts, try again later.");
// Do something with too many attempts, e.g. display error message for user.
Err(fars::Error::ApiError {
status_code,
error_code,
response,
}
.into())
},
| _ => {
eprintln!(
"API error: ({:?}) {:?} - {:?}",
status_code, error_code, response
);
// Do something with other errors.
Err(fars::Error::ApiError {
status_code,
error_code,
response,
}
.into())
},
}
},
// Internal errors
| _ => {
eprintln!("Internal error: {:?}", error);
// Do something with internal errors.
Err(error.into())
},
}
},
}
}