Skip to content

Commit c9cad8c

Browse files
author
Bart Veneman
committed
send origin server errors back to the frontend
1 parent 9af013f commit c9cad8c

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

api/v2/_extract-css-basic.js

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,8 +80,26 @@ export function getStyles(nodes) {
8080
return items
8181
}
8282

83+
export class HttpError extends Error {
84+
constructor({ url, statusCode, statusText }) {
85+
this.url = url
86+
this.statusCode = statusCode
87+
this.statusText = statusText
88+
this.message = `The origin server at "${url}" errored with status ${statusCode} (${statusText})`
89+
}
90+
}
91+
8392
export async function extractCss(url) {
84-
var { body, headers } = await got(url)
93+
let body = ''
94+
let headers = {}
95+
96+
try {
97+
var response = await got(url)
98+
body = response.body
99+
headers = response.headers
100+
} catch (error) {
101+
throw new HttpError({ url, statusCode, statusText })
102+
}
85103

86104
// Return early if our response was a CSS file already
87105
if (headers['content-type'].includes('text/css')) {
@@ -117,7 +135,11 @@ export async function extractCss(url) {
117135
// And c'mon, don't @import inside your @import.
118136
var importUrls = getImportUrls(item.css)
119137
if (importUrls.length > 0) {
120-
var cssRequests = importUrls.map(importUrl => getCssFile(resolveUrl(importUrl, url)))
138+
var cssRequests = importUrls.map(
139+
importUrl => getCssFile(resolveUrl(importUrl, url))
140+
// silently fail on sub-resources
141+
.catch(_ => '')
142+
)
121143
var importedFiles = await Promise.all(cssRequests)
122144
importedFiles.map((css, index) => {
123145
result.push({

api/v2/extract-css.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { isUrl } from '../_is-url.js'
2-
import { extractCss } from './_extract-css-basic.js'
2+
import { extractCss, HttpError } from './_extract-css-basic.js'
33

44
export default async (req, res) => {
55
const { url } = req.query
@@ -26,6 +26,15 @@ export default async (req, res) => {
2626
const css = result.map(({ css }) => css).join('\n')
2727
return res.end(css)
2828
} catch (error) {
29+
if (error instanceof HttpError) {
30+
res.statusCode = error.statusCode
31+
return res.json({
32+
url,
33+
statusCode: error.statusCode,
34+
statusText: error.statusText,
35+
message: error.message,
36+
})
37+
}
2938
res.statusCode = 500
3039
return res.json({ message: error.message })
3140
}

0 commit comments

Comments
 (0)