How do I render a view as a response of an Exception?


#1

From Gitter: https://gitter.im/adonisjs/adonis-framework?at=59ddf870e44c43700a1cacfc

@virk

How do i access the view property on an exception to ie. render a 404 page ?
in 3.x we could use yield response.sendView('welcome') but now it seems impossible.

ie. Something like that:

'use strict';

const MapErrorStatusToView = {
  404: 'frontend.404',
};

/**
 * This class handles all exceptions thrown during
 * the HTTP request lifecycle.
 *
 * @class ExceptionHandler
 */
class ExceptionHandler {
  /**
   * Handle exception thrown during the HTTP lifecycle
   *
   * @method handle
   *
   * @param  {Object} error
   * @param  {Object} options.request
   * @param  {Object} options.response
   *
   * @return {void}
   */
  async handle (error, { request, response, view }) {
    // Detect 404 errors. TODO: Less hack. More beautiful code.
    if (error.status == 404) {
      return response
        .status(error.status)
        .sendView(MapErrorStatusToView[error.status]);
    }
  }

  /**
   * Report exception for logging or debugging.
   *
   * @method report
   *
   * @param  {Object} error
   * @param  {Object} options.request
   *
   * @return {void}
   */
  async report (error, { request }) {
    // TODO: do report the error somewhere.
  }
}

module.exports = ExceptionHandler;

#2

+1
And how to keep beautiful error pages on development, but in production to show custom pages.
On Adonis v3 it could be done kinda like this:

const status = error.status || 500

if (Env.get('NODE_ENV') === 'development') {
  const youch = new Youch(error, request.request)
  const type = request.accepts('json', 'html')
  const formatMethod = type === 'json' ? 'toJSON' : 'toHTML'
  const formattedErrors = await youch[formatMethod]()
  response.status(status).send(formattedErrors)
  return
}

return response.status(status).sendView('errors.index', {error})

#3

Hey :wave:

So in order to send a view you can use this.

if (error.status === 404) {
  return response.send(view.render('errors.404'))
}

and if you want to add Youch to your error handling you can take example of this code: adonis-framework/src/App/Handler.js:86


#4

When I try, I get

ReferenceError: view is not defined


#5

Have you unpacked the view variable from the HTTPContext?

async handle (error, { view }) {
  // ...
}