Skip to content

Commit e8f1a7d

Browse files
Change some error handling stuff
1 parent 29b3068 commit e8f1a7d

File tree

2 files changed

+14
-9
lines changed

2 files changed

+14
-9
lines changed

README.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,11 @@ This has built-in types.
1818
To create an inbox, you can use one of the following two functions:
1919
```js
2020
//with callback
21-
createInbox((inbox) => {
21+
createInbox((inbox, err) => {
22+
if(err) {
23+
return console.error(err);
24+
}
25+
2226
console.log(`Created new inbox: ${inbox.address}, token: ${inbox.token}`);
2327
});
2428

src/index.ts

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,12 @@ const BASE_URL = "https://api.tempmail.lol";
1111
* Create a new Inbox.
1212
* @param cb {function} Callback function.
1313
*/
14-
function createInbox(cb: (inbox: Inbox) => any): void {
15-
fetch(`${BASE_URL}/generate`).then(res => res.json()).then(json => {
14+
function createInbox(cb: (inbox: Inbox | undefined, err: Error | null) => any): void {
15+
fetch(`${BASE_URL}/generate`).then(res => res.json()).then((json) => {
1616
const inbox = new Inbox(json.address, json.token);
17-
cb(inbox);
17+
cb(inbox, null);
18+
}).catch((err) => {
19+
cb(undefined, err);
1820
});
1921
}
2022

@@ -32,9 +34,8 @@ async function createInboxAsync(): Promise<Inbox> {
3234
* Check for new emails on an Inbox.
3335
* @param inbox {Inbox | string} Inbox or token string to check.
3436
* @param cb {function} Callback function.
35-
* @throws {Error} If the token is not valid.
3637
*/
37-
function checkInbox(inbox: Inbox | string, cb: (emails: Email[]) => any): void {
38+
function checkInbox(inbox: Inbox | string, cb: (emails: Email[], err: Error | null) => any): void {
3839

3940
//convert the token to an Inbox
4041
if(typeof inbox === "string") {
@@ -43,13 +44,13 @@ function checkInbox(inbox: Inbox | string, cb: (emails: Email[]) => any): void {
4344

4445
fetch(`${BASE_URL}/auth/${inbox.token}`).then(res => res.json()).then(json => {
4546
if(json.token === "invalid") {
46-
throw new Error("Invalid token");
47+
cb([], new Error("Invalid token"));
4748
}
4849
if(json.email === null) {
49-
return cb([]);
50+
return cb([], null);
5051
}
5152
const emails = json.email.map((email: Email) => new Email(email.from, email.to, email.subject, email.body, email.html, email.date));
52-
cb(emails);
53+
cb(emails, null);
5354
});
5455
}
5556

0 commit comments

Comments
 (0)