Error handling

Enter in your browser http://localhost:3000/bla-bla-bla   or change the value in the this.render('index') line on a non-existent template.   In each case, you will see how the server reacts to errors.

Areto blog error page 400

Capture errors

To intercept and handle exceptions, add a configuration section containing the controller (by default DefaultController) and an action (by default error). These parameters provide error handling.

config/default.js

module.exports = {
  ...
  'errors': {
    // Controller: require('../controller/DefaultController'),
    // action: 'error'
  }
};

Action on error

Create the actionError method in controller. It will be called to handle errors.

controller/DefaultController.js

actionError () {
  // returned HTTP error code (404, 403, 500)
  this.setStatus(this.err.status);
  // select the template corresponding error code
  switch (this.err.status) {
    case 403:
    case 404:
      this.render(this.err.status);
      break;
    default:
      this.render(500);
}

Error views

Create templates for error status (403, 404, 500). They will be displayed to user.

view/template/default/403.ejs

<% layout(view.get('_layouts/main')) -%>
<div class="row">
  <div class="col-sm-8 col-sm-offset-2 col-lg-6 col-lg-offset-3">
    <div class="error-page">
      <div class="text-center">
        <h1 class="text-danger">Access is denied</h1>
        <p>Access is restricted to authorized users.</p>
      </div>
    </div>
  </div>
</div>
Areto blog error page 404

view/template/default/404.ejs

<% layout(view.get('_layouts/main')) -%>
<div class="row">
  <div class="col-sm-8 col-sm-offset-2 col-lg-6 col-lg-offset-3">
    <div class="error-page">
      <div class="text-center">
        <h1 class="text-danger">Page not found</h1>
        <p>We did not find the page you requested.</p>
      </div>
    </div>
  </div>
</div>
Areto blog error page 500

view/template/default/500.ejs

<% layout(view.get('_layouts/main')) -%>
<div class="row">
  <div class="col-sm-8 col-sm-offset-2 col-lg-6 col-lg-offset-3">
    <div class="error-page">
      <div class="text-center">
        <h1 class="text-danger">Server error</h1>
        <p>We are working to resolve this problem now.</p>
      </div>
    </div>
  </div>
</div>

Now repeat the example from the beginning of the chapter and see how to change the server's response.