Skip to content

Instantly share code, notes, and snippets.

@bitkidd
Created July 12, 2019 14:22
Show Gist options
  • Select an option

  • Save bitkidd/a87974b5ac4db6da704d9d8b39422546 to your computer and use it in GitHub Desktop.

Select an option

Save bitkidd/a87974b5ac4db6da704d9d8b39422546 to your computer and use it in GitHub Desktop.

Revisions

  1. bitkidd created this gist Jul 12, 2019.
    50 changes: 50 additions & 0 deletions example.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    const BaseExceptionHandler = use('BaseExceptionHandler');
    const Logger = use('Logger');

    class ExceptionHandler extends BaseExceptionHandler {
    async handle(error, { request, response, session, view }) {
    const isJSON = request.accepts(['html', 'json']) === 'json';
    const production = process.env.NODE_ENV === 'production';

    if (error.code === 'E_INVALID_SESSION') {
    session.flash({
    flash_error: 'You have to login/sign up to access this page.'
    });
    await session.commit();
    response.route('login');
    return;
    }

    if (error.code === 'E_VALIDATION_FAILED' && !isJSON) {
    session.withErrors(error.messages).flashAll();
    await session.commit();
    response.redirect('back');
    return;
    }

    // handle if production
    if (production && !isJSON) {
    return response.send(view.render('errors.index', { error }));
    }

    if (isJSON) {
    return response.status(error.status).send({
    code: error.code,
    status: error.status,
    errors: error.messages,
    name: error.name
    });
    }

    // handle all other
    super.handle(...arguments);
    }

    async report(error, {}) {
    if (error.code !== 'E_INVALID_SESSION') {
    Logger.info(error);
    }
    }
    }

    module.exports = ExceptionHandler;