上QQ阅读APP看书,第一时间看更新
How to do it...
You will build a custom error handler that sends to the client the error message.
- Create a new file named custom-error-handler.js
- Include the ExpressJS library, then initialize a new ExpressJS application:
const express = require('express') const app = express()
- Define a new Route Method to handle GET requests for path "/" and throw an error every time:
app.get('/', (request, response, next) => { try { throw new Error('Oh no!, something went wrong!') } catch (err) { next(err) } })
- Define a custom error handler middleware function to send the error message back to the client's browser:
app.use((error, request, response, next) => { response.end(error.message) })
- Listen on port 1337 for new connections:
app.listen( 1337, () => console.log('Web Server running on port 1337'), )
- Save the file
- Open a terminal and run:
node custom-error-handler.js
- To see the result, in your web browser, navigate to:
http://localhost:1337/