Skip to content

Commit

Permalink
feat(error): generic error handler for API requests
Browse files Browse the repository at this point in the history
  • Loading branch information
lirantal committed Sep 23, 2017
1 parent 3e2644f commit cd56b58
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 6 deletions.
29 changes: 29 additions & 0 deletions server/lib/helpers/ApiError.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
'use strict'

const ApiErrorCodes = {
serverError: 'SERVER_ERROR'
}

class ApiError extends Error {
constructor (message, {status, code} = {}) {
super(message)

// Set Generic error message
this.message = message

// Set HTTP status code
this.status = status || 500

// Set API error code
this.code = code || ApiErrorCodes.serverError

// Ensures that stack trace uses our subclass name
this.name = this.constructor.name

// Ensures the ApiError subclass is sliced out of the
// stack trace dump for clarity
Error.captureStackTrace(this, this.constructor)
}
}

module.exports = ApiError
8 changes: 6 additions & 2 deletions server/lib/services/express.js
Original file line number Diff line number Diff line change
Expand Up @@ -166,8 +166,12 @@ module.exports.initErrorRoutes = function (app) {
// Log it
console.error(err.stack);

// Redirect to error page
res.status(500).send();
// Build an error response object and send it with the
// status in the error
res.status(err.status).send({
message: err.message,
code: err.code
});
});
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
*/
const path = require('path')
const config = require(path.resolve('./lib/config'))
const ApiError = require(path.resolve('./lib/helpers/ApiError'))
const errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'))
const mongoose = require('mongoose')
const passport = require('passport')
Expand All @@ -22,12 +23,12 @@ var noReturnUrls = [
/**
* Signup
*/
exports.signup = async function (req, res) {
exports.signup = async function (req, res, next) {
try {
const user = await UserService.signUp(req.body)
return res.json(user)
} catch (err) {
return res.status(500).send(err.message)
return next(new ApiError(err.message))
}
}

Expand All @@ -49,7 +50,7 @@ exports.signout = function (req, res) {
/**
* Jwt Token Auth
*/
exports.token = async function (req, res) {
exports.token = async function (req, res, next) {
try {
// Authenticate the user based on credentials
// @TODO be consistent with whether the login field for user identification
Expand All @@ -69,7 +70,7 @@ exports.token = async function (req, res) {

res.status(200).json({token: token})
} catch (err) {
return res.status(500).send(err.message)
return next(new ApiError(err.message))
}
}

Expand Down

0 comments on commit cd56b58

Please sign in to comment.