Skip to content

Commit

Permalink
feat(runtime): catch image exceptions and prevent page crash (#43)
Browse files Browse the repository at this point in the history
* feat(runtime): catch image exceptions and prevent global crash

* fix: unify error handle
  • Loading branch information
farnabaz authored Oct 21, 2020
1 parent 27c3445 commit e5190c1
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 10 deletions.
1 change: 1 addition & 0 deletions playground/layouts/default.vue
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,6 @@ body {
background: #111111;
display: flex;
flex-direction: column;
color: #ffffff;
}
</style>
39 changes: 29 additions & 10 deletions src/runtime/nuxt-image-mixins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ export default {
},
data () {
return {
error: '',
srcset: [],
blurry: null,
loading: false,
Expand All @@ -73,7 +74,7 @@ export default {
},
async fetch () {
if (!this.legacy) {
this.blurry = await this.$img.lqip(this.src)
this.blurry = await this.getPlaceholder()
}
},
mounted () {
Expand Down Expand Up @@ -132,7 +133,7 @@ export default {
},
watch: {
async src () {
this.blurry = await this.$img.lqip(this.src)
this.blurry = await this.getPlaceholder()
this.original = null
if (!this.legacy) {
this.$img.$observer.remove(this.$el)
Expand All @@ -144,15 +145,28 @@ export default {
}
},
methods: {
getPlaceholder () {
try {
return this.$img.lqip(this.src)
} catch (e) {
this.onError(e)
return false
}
},
generateSizedImage (width: number, height: number, format: string) {
const image = this.$img(this.src, {
width,
height,
format,
fit: this.fit,
...this.operations
})
return encodeURI(image)
try {
const image = this.$img(this.src, {
width,
height,
format,
fit: this.fit,
...this.operations
})
return encodeURI(image)
} catch (e) {
this.onError(e)
return ''
}
},
loadOriginalImage () {
this.loading = true
Expand All @@ -167,6 +181,11 @@ export default {
...this.imgAttributes,
...extraAttributes
})
},
onError (e: Error) {
this.error = e.message
// eslint-disable-next-line no-console
console.error(e.message)
}
},
beforeDestroy () {
Expand Down
5 changes: 5 additions & 0 deletions src/runtime/nuxt-image.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ export default {
}
},
render (h) {
if (this.error) {
return h('div', {
class: ['__nim_w'].concat(this.$attrs.class || '')
}, [this.error])
}
if (this.legacy) {
return this.renderLegacy(h)
}
Expand Down
5 changes: 5 additions & 0 deletions src/runtime/nuxt-picture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ export default {
}
},
render (h) {
if (this.error) {
return h('div', {
class: ['__nim_w'].concat(this.$attrs.class || '')
}, [this.error])
}
if (this.legacy) {
return this.renderLegacy(h)
}
Expand Down

0 comments on commit e5190c1

Please sign in to comment.