How to do it...

You will build a custom error handler that sends to the client the error message.

  1. Create a new file named custom-error-handler.js
  2. Include the ExpressJS library, then initialize a new ExpressJS application:
     const express = require('express') 
     const app = express() 
  1. 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) 
           } 
      }) 
  1. 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) 
      }) 
  1. Listen on port 1337 for new connections:
      app.listen( 
          1337, 
          () => console.log('Web Server running on port 1337'), 
      ) 
  1. Save the file
  2. Open a terminal and run:
      node custom-error-handler.js
  1. To see the result, in your web browser, navigate to:
      http://localhost:1337/
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.196.234