Skip to content

Instantly share code, notes, and snippets.

View gisderdube's full-sized avatar

Lukas Gisder-Dubé gisderdube

View GitHub Profile
@gisderdube
gisderdube / try_catch.js
Created November 13, 2018 11:44
Basic try ... catch
const a = 5
try {
console.log(b) // b is not defined, so throws an error
} catch (err) {
console.error(err) // will log the error with the error stack
}
console.log(a) // still gets executed
const a = 5
try {
console.log(b) // b is not defined, so throws an error
} catch (err) {
console.error(err) // will log the error with the error stack
} finally {
console.log(a) // will always get executed
}
myAsyncFunc(someInput, (err, result) => {
if(err) return console.error(err) // we will see later what to do with the error object.
console.log(result)
})
Promise.resolve(1)
.then(res => {
console.log(res) // 1
throw new Error('something went wrong')
return Promise.resolve(2)
})
.then(res => {
console.log(res) // will not get executed
;(async function() {
try {
await someFuncThatThrowsAnError()
} catch (err) {
console.error(err) // we will make sense of that later
}
console.log('Easy!') // will get executed
})()
class CustomError extends Error {
constructor(code = 'GENERIC', status = 500, ...params) {
super(...params)
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CustomError)
}
this.code = code
this.status = status
const express = require('express')
const router = express.Router()
const CustomError = require('../CustomError')
router.use(async (req, res) => {
try {
const route = require(`.${req.path}`)[req.method]
try {
const result = route(req) // We pass the request to the route function
const CustomError = require('../CustomError')
const GET = req => {
// example for success
return { name: 'Rio de Janeiro' }
}
const POST = req => {
// example for unhandled error
throw new Error('Some unexpected error, may also be thrown by a library or the runtime.')
import React, { Component } from 'react'
import GlobalError from './GlobalError'
class Application extends Component {
constructor(props) {
super(props)
this.state = {
error: '',
import React, { Component } from 'react'
class GlobalError extends Component {
render() {
if (!this.props.error) return null
return (
<div
style={{
position: 'fixed',