Created
July 12, 2019 14:22
-
-
Save bitkidd/a87974b5ac4db6da704d9d8b39422546 to your computer and use it in GitHub Desktop.
Adonis.js v4 example exception handler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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