kriasoft / universal-router

A simple middleware-style router for isomorphic JavaScript web apps
https://www.kriasoft.com/universal-router/
MIT License
1.7k stars 104 forks source link

Improve error handling logic #147

Closed frenzzy closed 6 years ago

frenzzy commented 6 years ago

Add an option for global error handling:

import UniversalRouter from 'universal-router'

const routes = [
  { path: '/one', action: () => '<h1>Page One</h1>' },
  { path: '/two', action: () => '<h1>Page Two</h1>' }
]

const options = {
  errorHandler(error) { // <= new option
    console.error(error)
    console.dir(error.context)
    return error.code === 404
      ? '<h1>Page Not Found</h1>'
      : '<h1>Oops! Something went wrong</h1>'
  }
}

const router = new UniversalRouter(routes, options)

router.resolve('/random').then(result => {
  document.body.innerHTML = result
  // renders: <h1>Page Not Found</h1>
})
coveralls commented 6 years ago

Coverage Status

Coverage remained the same at 100.0% when pulling 122072d7a4ec0a871a43e6d2ef2b5397f84e9e8e on frenzzy:error-handler into 30a82112813d19ebef5302e964cc9a21928d5323 on kriasoft:master.