Skip to content

Instantly share code, notes, and snippets.

@AyozeVera
Last active April 23, 2018 16:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AyozeVera/af89c828270b304d532a1f23c98dde17 to your computer and use it in GitHub Desktop.
Save AyozeVera/af89c828270b304d532a1f23c98dde17 to your computer and use it in GitHub Desktop.
AdonisJS Handler code for retrieving errors as JSON instead of HTML
'use strict'
/**
* 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 }) {
let jsonResponse = { name: error.name, message: error.message, status: error.status }
switch (error.name) {
case 'ModelNotFoundException':
return await response.status(error.status).json({ ...jsonResponse, message: 'Not found' })
case 'InvalidJwtToken':
return await response.status(error.status).json({ ...jsonResponse, message: 'Not valid authentication' })
default:
return await response.status(error.status).json(jsonResponse)
}
}
/**
* Report exception for logging or debugging.
*
* @method report
*
* @param {Object} error
* @param {Object} options.request
*
* @return {void}
*/
async report (error, { request }) {
}
}
module.exports = ExceptionHandler
@AyozeVera
Copy link
Author

This gist will be continually improved

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment