Skip to content

Instantly share code, notes, and snippets.

@bitkidd
Created July 12, 2019 14:22
Show Gist options
  • Save bitkidd/a87974b5ac4db6da704d9d8b39422546 to your computer and use it in GitHub Desktop.
Save bitkidd/a87974b5ac4db6da704d9d8b39422546 to your computer and use it in GitHub Desktop.
Adonis.js v4 example exception handler
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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment