Skip to content

Commit 9cf68b4

Browse files
committed
trycatch
1 parent fa7fbf7 commit 9cf68b4

File tree

3 files changed

+61
-29
lines changed

3 files changed

+61
-29
lines changed

index.js

Lines changed: 30 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
const cheerio = require('cheerio')
22
const fetch = require('node-fetch')
3-
43
const toJson = require('./utils/tojson')
54

65
const defaultOptions = {
@@ -11,33 +10,36 @@ const defaultOptions = {
1110
}
1211

1312
const htmlTableToJson = async (options = defaultOptions, headers) => {
14-
const { url, html, selector, format } = { ...defaultOptions, ...options }
15-
16-
let data
17-
18-
if (url) {
19-
const response = await fetch(url)
20-
data = await response.text()
21-
} else if (html) {
22-
data = html
23-
} else {
24-
return []
25-
}
26-
27-
const $ = cheerio.load(data)
28-
29-
if ($('table').html() === null) {
30-
throw new Error(
31-
`Please provide ${url ? 'url' : 'html'} which contains table`
32-
)
33-
}
34-
35-
let body = toJson($, selector, headers)
36-
37-
if (format === 'json') {
38-
return JSON.stringify(body)
39-
} else {
40-
return body
13+
try {
14+
const { url, html, selector, format } = { ...defaultOptions, ...options }
15+
16+
let data
17+
18+
if (url) {
19+
const response = await fetch(url)
20+
data = await response.text()
21+
} else if (html) {
22+
data = html
23+
} else {
24+
return []
25+
}
26+
27+
const $ = cheerio.load(data)
28+
29+
if ($('table').html() === null) {
30+
throw new Error(
31+
`Please provide ${url ? 'url' : 'html'} which contains table`
32+
)
33+
}
34+
35+
let body = toJson($, selector, headers)
36+
if (format === 'json') {
37+
return JSON.stringify(body)
38+
} else {
39+
return body
40+
}
41+
} catch (e) {
42+
throw new Error(e)
4143
}
4244
}
4345

package-lock.json

Lines changed: 30 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
},
2222
"homepage": "https://github.com/acharyaroshanji/jsonfromtable#readme",
2323
"dependencies": {
24+
"axios": "^0.19.2",
2425
"cheerio": "^1.0.0-rc.3",
2526
"node-fetch": "^2.6.0"
2627
}

0 commit comments

Comments
 (0)